What are the rules for object reference casting?
-A reference of any object can be cast to a reference of type 'Object'.
-An object cannot be casted to a primitive type or vice-versa.
-An interface type can be converted to another interface type or to an object. If the new type is an interface, it must be a superinterface of the old type.
-A class type can be converted to a class type or to an interface type. If converting to a class type the new type should be superclass of the old type. If converting to an interface type to a new type, then old class must implement the interface
-While casting an object reference to an array type reference, the object must be an array of a component type that is compatible with the component type of the array type reference
e.g.
double values[] = {1.95, 1.2768, 3.765};
int intValues[] = (int) values; // compile-error
Moreover,if you cast up the class hierarchy you do not have to use the cast operator; if you are casting down the class hierarchy you must use the cast operator:One can cast up or down the hierarchy but cannot sideways.It is possible to deceive compiler while typecasting an object but it is decided at the runtime how an object type is converted.
-An object cannot be casted to a primitive type or vice-versa.
-An interface type can be converted to another interface type or to an object. If the new type is an interface, it must be a superinterface of the old type.
-A class type can be converted to a class type or to an interface type. If converting to a class type the new type should be superclass of the old type. If converting to an interface type to a new type, then old class must implement the interface
-While casting an object reference to an array type reference, the object must be an array of a component type that is compatible with the component type of the array type reference
e.g.
double values[] = {1.95, 1.2768, 3.765};
int intValues[] = (int) values; // compile-error
Moreover,if you cast up the class hierarchy you do not have to use the cast operator; if you are casting down the class hierarchy you must use the cast operator:One can cast up or down the hierarchy but cannot sideways.It is possible to deceive compiler while typecasting an object but it is decided at the runtime how an object type is converted.