The following reference variable casting is confusing to me :
I want to know the detailed mechanism of casting happens at line 8. And why do i have to cast the reference variable explicitly ? At line 8, doesn't it mean that reference variable subC is directed to an object of type SubClass ?
Sun Certified Programmer for the Java 2 Platform, Standard Edition 5.0 (88 %)
The object is created by calling new SubClass(), so the object's true runtime type is SubClass.
The variable "superC" has a type of SuperClass, so when a reference to the new SubClass object is assigned to superC, that reference is automatically upcast to type SuperClass. This can be done implicitly (without an explicit cast) because upcasting (moving up the inheritance hierarchy) is always safe. The reason is that any instance of SubClass is also an instance of SuperClass.
But now consider the line...
The variable "subC" has a type of SubClass, but the reference being assigned to it (stored by the variable superC) has a type of SuperClass. Downcasting (moving down the inheritance hierarchy) is not always safe, because there could be instances of SuperClass that are not instances of SubClass. Therefore, an explicit cast is required to assure the compiler that the object referenced by superC is, in fact, an instance of SubClass.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Joined: Jul 08, 2008
How about this :
Here, the object is a type of SuperClass, then why the compiler allows the explicit cast?
You can cast an instance of a class always to that class.
Because of the cast in the sample
SubClass subC = (SuperClass)superC;
(regardless whether superC is of type SuperClass or SubClass) the compiler will consider the object on the right as being of type SuperClass. Such an object can not be assigned to a variable of type SubClass. Therefore that sample will not compile.