I need to get a better grasp of the difference between 'runtime' &
'compile time', other than the obvious connotation. In particular, I'm confused how the JVM will compile a program with no errors but at runtime the program could get a ClassCastException error.
For example, below is some code from Schaums
JAVA DATA STRUCTURES where I don't understand the author's comment, 'RUN-TIME ERROR: xx cannot be cast as a Y'; since the "yy = (Y)xx;" cast is OK why does the program croak on the last line?
class X { public
String toString() { return "I am an X."; } }
class Y extends X { public String toString() { return "I am a Y."; } }
public class Ex0304
{ public static void main(String[] args)
{ Y y = new Y();
System.out.println("y: " + y);
X x = y;
System.out.println("x: " + x);
Y yy = (Y)x; // casts x as type Y
System.out.println("yy: " + yy);
X xx = new X();
System.out.println("xx: " + xx);
yy = (Y)xx; // RUN-TIME ERROR: xx cannot be cast as a Y
System.out.println("yy: " + yy);
}
}
Thanks much!
Dan
[ October 18, 2005: Message edited by: Dan Bromberg ]