Lecture 2 - RunTime Casting
//X is a supper class of Y and Z which are siblings.
class X{}
class Y extends X{}
class Z extends X{}
public class RunTimeCastDemo{
public static void main(String args[]){
X x = new X();
Y y = new Y();
Z z = new Z();
X xy = new Y(); // compiles ok
X xz = new Z(); // compiles ok
Y yz = new Z(); // incompatible type (siblings), error
Y y1 = new X(); // X is not a Y, error
Z z1 = new X(); // X is not a Z, error
X x1 = y; // compiles ok (y is subclass of X), upcast
X x2 = z; // compiles ok (z is subclass of X), upcast
Y y1 = (Y) x; // compiles ok but produces runtime error
Z z1 = (Z) x; // compiles ok but produces runtime error
Y y2 = (Y) x1; // compiles and runs ok (x1 is type Y), downcast
Z z2 = (Z) x2; // compiles and runs ok (x2 is type Z), downcast
Y y3 = (Y) z; // inconvertible types (siblings), error
Z z3 = (Z) y; // inconvertible types (siblings), error
Object o = z; // OK, upcast
Y o1 = (Y) o; // compiles ok but produces runtime error
}
}