Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 { }
like image 661
sHAILU Avatar asked Dec 02 '22 20:12

sHAILU


1 Answers

A Tree is not necessarily a Redwood, but it could be, hence the lack of a compile-time error.

In this case it's pretty obvious it isn't, but compilers tend to complain about things that are definitely incorrect, rather than probably or possibly incorrect. In this case the logic is incorrect, not the code itself, and logic is your problem, not the compiler's.

Tree t = new Redwood();
Redwood r = (Redwood) t;

Perfect valid at both compile and run time.

like image 51
Mike Avatar answered Dec 04 '22 10:12

Mike