aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Reference variable casting mechanism Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Reference variable casting mechanism" Watch "Reference variable casting mechanism" New topic
Author

Reference variable casting mechanism

Faber Siagian
Ranch Hand

Joined: Jul 08, 2008
Posts: 52
Dear Ranchers,

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 %)
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

First, consider the line...

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
Faber Siagian
Ranch Hand

Joined: Jul 08, 2008
Posts: 52
How about this :



Here, the object is a type of SuperClass, then why the compiler allows the explicit cast?
Ralph Jaus
Ranch Hand

Joined: Apr 27, 2008
Posts: 342
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.


SCJP 5 (98%) - SCBCD 5 (98%)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reference variable casting mechanism