转换变量,不确定为什么会给出 ClassCastException

Casting a variable, not sure why it gives a ClassCastException

我们有以下代码:

我们有这条指令:

mySub = (SubClass) mySuper;

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

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.