class Alpha {}
class Beta extends Alpha {}
class Chi extends Alpha {}
public class CastTest {
public static void main(String [] args) {
Alpha a = new Alpha();
Beta b = new Beta();
Chi c = new Chi();
a=b;
//b=c; //need explicit cast
b = (Beta)a; //should be OK to downcast
//b = (Beta)c; //can't cast to sibling classes
//c = (Alpha)c; //same as saying c=a
}
}
This is what I think:
1)[ a=b ] will work because b is a subclass of a so its implicitly cast.
2)[ b=c ] needs explicit cast since its a downcast (compile error)
3) [ b = (Beta)a] should be ok since it is explicitly downcasted (no runtime error for me)
4) [ b = (Beta)c ] can't cast to sibling classes (compile error)
5) [ c = (Alpha)c] same as 2.. can't make c=a since that is a downcast
So it looks like 1 and 3 will compile and run.
And 2,4,5 are all compile time errors. Is this correct?
Henry