【问题标题】:Casting a variable, not sure why it gives a ClassCastException转换一个变量,不知道为什么它会给出一个 ClassCastException
【发布时间】:2015-01-23 07:18:11
【问题描述】:

我们有以下代码:

我们有这个指令:

mySub = (SubClass) mySuper;

对我来说,这看起来像是一个合法的强制转换,但它给出了 ClassCastException。为什么会这样?

【问题讨论】:

  • 您可以将子类的实例强制转换为其超类,但反之则不行。
  • @RobbyCornelissen 例如 mySuper = (SuperClass) mySub ?
  • 只要 Super 引用子类对象,从 Super 向下转换到 Sub 就可以了。在这种情况下 Super 引用一个 Super 对象。如果你必须向下转换,请进行类型检查
  • @Michiel 确实如此。
  • @LewsTherin 我的评论是关于底层实例的,你的评论是关于引用类型的。

标签: inheritance casting


【解决方案1】:

ClassCastException

来自 Oracle 文档..

抛出表明代码已尝试将对象强制转换为它不是实例的子类。例如,以下代码生成 ClassCastException:

 Object x = new Integer(0);
 System.out.println((String)x);

Eg:  Object x = new Integer(0);         //works fine 
     String s = (String)x;      //Will raise an exception here as Object 
                                    is not a subclass of String.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    相关资源
    最近更新 更多