在编译时的向下/向上转换错误&运行? [英] Downcasting/Upcasting error at compile time & runtime?

查看:385
本文介绍了在编译时的向下/向上转换错误&运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请检查以下程序。

我怀疑编译器会在编译器级别发出转换异常,何时会在 runtime

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

像下面的程序一样,表达式

Like in below program, expression

我假设应该在编译时失败,因为Tree不是Redwood。但它不会在编译时中失败,因为预期它在运行时失败 !!!

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 { }


推荐答案

编译器只会查看表达式的编译时类型。它不对表达式的运行时类型做假设。 new Tree()有编译时类型 Tree ,因此(Redwood)myTreeVariable 没有区别。

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.

这篇关于在编译时的向下/向上转换错误&运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆