Search code examples
javainheritancecastingtype-conversiondowncast

Downcasting/Upcasting error at compile time & runtime?


Please check the below program.

I have doubt when compiler will issue casting exception at compiler level and when it will be at runtime?

Like in below program, expression

I assumed (Redwood) new Tree() should have failed at compiler time as Tree is not Redwood. But it is not failing in compile time, as expected it failed during runtime!!!

public class Redwood extends Tree {
     public static void main(String[] args) {
         new Redwood().go();
     }
     void go() {
         go2(new Tree(), new Redwood());
         go2((Redwood) new Tree(), new Redwood());
     }
     void go2(Tree t1, Redwood r1) {
         Redwood r2 = (Redwood)t1;
         Tree t2 = (Tree)r1;
     }
 }
 class Tree { }

Solution

  • The compiler will just look at the compile-time type of the expression. It does not do assumptions on the runtime type of the expression. new Tree() has compile-time type Tree, so (Redwood)new Tree() is no different from (Redwood)myTreeVariable.