Hi!
I was confused with the same mock exam question.
An exerpt from Java 1.4 Certification book (pg 123, Object Reference Casting section):
"...The rules for casting are broader than those for conversion. Some of these rules concern reference type and can be enforced by the compiler at compile time; other rules concern class and can be enforced only during execution.
...
When both OLDTYPE and NEWTYPE are classes, one class must be a subclass of the other."
It is the case we have here (Sub class is a subclass of Base class).
In the same section:
"Assuming that a desired cast survives compilation, a second check must occur at RUNTIME. The second check determines whether the class of the object being cast is compatible with the new type...
Here, COMPATIBLE means that the class can be converted according to the conversion rules...:
If NEWTYPE is a class, the class of the expression being converted must be NEWTYPE or must inherit from NEWTYPE."
The case we have here is:
NEWTYPE is Sub, OLDTYPE is Base.
Base doesn't inherit from Sub
nor is the Base class equal to Sub class
BUT Base and Sub classes' implementation is THE SAME.
For me it's not logical that the latter runtime check isn't enough to get error free program run (as Dan said) - but I guess there are things we just have to accept even though they aren't too logical
Why does compiler not "filter out" this case (base class to subclass cast) if we are going to get runtime exception anyway??
I hope I'm not too confusing :roll:
Thank You very much!!!
Stasha