Re: Java downcast question
Chad wrote:
Given the following code...
class X {}
class Y extends X {}
class Z extends X {}
public class Main {
public static void main(String[] args) {
X x = new X();
Y y = new Y();
Z z = new Z();
Y o6 = (Y) x; //<--error
}
}
I get...
run:
Exception in thread "main" java.lang.ClassCastException: X cannot be
cast to Y
at Main.main(Main.java:12)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Why can't I downcast X to Y? Y inherits X.
I think you may be confusing two types of errors, compile time and
runtime. I don't know how you are doing your building and running, but
separating the two steps may help you keep the different sets of errors
clear.
The "BUILD SUCCESSFUL" means that you had no compile time errors. The
compiler rejects only casts that cannot possibly be valid. Because Y
extends X, x might reference a Y, in which case the cast to Y would be
valid, so the compiler accepts it.
At run time, the JVM ensures that reference types always tell the truth.
A Y reference must be null or a pointer to an object of class Y, or a
pointer to an object whose class is a direct or indirect subclass of Y.
In fact, x references an X, not a Y. X is not a subclass of Y, so a Y
reference cannot point to an X object. The JVM detects this and throws
an exception at run time, when you attempt to execute the cast.
The reason for the asymmetry is the fact that, for example, Y might have
a public method that X lacks. It can't happen the other way round. If X
has a public method with a given name and argument types, so does Y,
either inherited from X or overridden.
Patricia