• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reference variable casting mechanism

 
Faber Siagian
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Faber Siagian
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about this :



Here, the object is a type of SuperClass, then why the compiler allows the explicit cast?
 
Ralph Jaus
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic