Java – downcasting / upcasting errors at compile time and runtime?

Please check the following procedure

I wonder when the compiler will emit a conversion exception at the compiler level and when it will be at run time?

Like the following program, express

I assume (Redwood) that the new tree () should fail at compile time because the tree is not redwood But it didn't fail at compile time, as expected at run time!

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 only looks at the compile - time type of the expression It does not assume the runtime type of an expression New tree() has compile time type tree, so (Redwood) new tree() is no different from (Redwood) mytreevariable

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>