This will fail at runtime because you can not cast a superclass to a subclass reference type. Compiler can only verify that the two types are in the same inheritance tree, which it is. It is possible that obj1 can be a DEF object, so it compiles.
Child class do have all the method of parent class, but Parent class does not know of any method of child class thats why it can not be downcasted to child class unless the object it referred to is of Chile class. While downcasting to more specific class instanceof operator must be used.
SCJP 5.0 -- 97%
Joined: Mar 12, 2008
As you said
Child class do have all the method of parent class, but Parent class does not know of any method of child class thats why it can not be downcasted to child class unless the object it referred to is of Chile class.
so based on this, the following code should compile and run properly
Even then The run time error is about the Class casting not with accessing a non-visible method.
Let's put it this way:
Suppose the runtime would not throw on line 2.
You'll have afterwards an ABC instance which says "hey, I'm a valid DEF", that means it respects DEF's contracts.
If so, one could try to invoke its display() method.
But wait ... does it have a display method!?
Not at all, because, although pretending to be a DEF, is in fact only a poor ABC.
So the runtime throws at line 2 already, making impossible to have living ABCs pretending to be DEFs, saving us from wrongly/error prone usage of those ABCs.
If you are allowed to cast the base class into derived class, No matter if you are using the methods of only the base class which are there, but no one is stopping you from using derived class methods as well , So if you use the derived class's methods ..it will throw exception..thats why it is not allowed to do the casting in this manner.
Joined: Mar 12, 2008
Thanks manoj and Cristian
Even though my doubt is cleared, i am more of feeling that this situation should be escalated at compile time itself rather than at runtime.
But don't know why they postponed it till run time. Any guesses ??