I still have some doubts on the question posed by Rajendra Deshpande :
He wrote :
Hi,
Here is a question that appeared in a mock
test.
class Y is a subclass of X. Will this compile?
X myX = new X();
Y myY = (Y) myX;
As i am given to understand, a class can be casted(hope i am using right term)to its superclass, but here we have (Y) myX,
where Y is a subclass of X. I think this should not compile.
However the correct answer appears to be is 'will compile' but 'not run'. Can someone shed light on this.
thanks.
-----------------------------------------------------------
My Doubt :
In this case the reference myX is initially initialized to an X object. On the second line we are downcasting it to a Y object which is a subclass of X.
The answer given was that compiler does not know till run time whether myX represents an X object or a Y object So it compiles. But during run time it is detected that the object is actually an X object. So it throws a ClassCastException (am i right here??).
My question is why isn't the compiler able to detect that the reference is pointing to an X object (even though the object is yet to be created) at compile time even though an explicit instantiation is made (x myX=new X()).
SJ