Hello all,
I'm somewhat confused with reference type casting. I want to clear things out, so I'll try to explain myself how to cast properly. I hope you'll point out the mistakes.
First, let's consider this two classes:
Let's start with the easy part;
Animal is a superclass of a Dog class, therefore Dog is a subclass of an Animal class. Every subclass
is a superclass object, thus class Dog
is an Animal. So assigning a subclass reference to a superclass, like so:
works perfectly. However,
a can refer only to superclass members, so the only thing we can call is an Animal getName() method. But since the getName() method in Dog overrides the method in Animal, the method returns the value defined in a Dog class. Example:
The output is "Class Dog".
As already said,
a can refer only to superclass members so calling any member from a subclass causes a compile-time error.
Conclusions of assigning a subclass reference to a superclass variable:
- can refer only to superclass members,
- overriden methods in a subclass are invoked instead of the ones in a superclass.
Now for the second part;
Every Dog
is an Animal, but not every Animal
is a Dog. That's why
Java does not allow statements like
They cause a compile time error. To avoid this error, one must explicilty cast the superclass reference to a subclass type, like so:
Unfortunatlely, this causes a run-time error, and I'm presuming this is because a superclass does not have an
is a relationship with a subclass. The way to check if such a relationship exits is to use an "instanceof" operator. Example follows:
Conclusions of assigning a superclass refrence to a subclass variable:
- superclasses must become subclasses in order to be able to assign them to subclass variables,
- instanceof operator helps to determine if a variable can be cast to some arbitrary type T.
Could you please point out the mistakes I made and mention other important facts I may have forgot? Also, if you don't mind, any example where the superclass must be cast to subclass in order to work properly will be greatly appreciated.
Thanks,
Ted.