尝试强制转换子类时发生ClassCastException

时间:2018-12-11 08:27:23

标签: java casting

我有此代码:

package Maven_test.Maven_project_test;

public class Test {
    class A {
        int i = 10;
    }

    class B extends A {
        int j = 20;
    }

    class C extends B {
        int k = 30;
    }

    public void pruebaJerarquia() {
        A a = new B();
        B b = (B) a;
        C c = (C) b;

        System.out.println(c.k);
    }
}

我想知道为什么这行:

C c = (C) b;

在执行程序时引发此异常:

Exception in thread "main" java.lang.ClassCastException: 
Maven_test.Maven_project_test.Test$B cannot be cast to 
Maven_test.Maven_project_test.Test$C
    at Maven_test.Maven_project_test.Test.pruebaJerarquia(Test.java:21)
    at Maven_test.Maven_project_test.App.main(App.java:10)

我认为这与向上转换和向下转换有关,但我不知道。可能是因为“ b”指向“ a”,并且由于“ C c =(C)b”,这就像尝试强制转换这样的内容一样?

C c = new A();

谢谢!

2 个答案:

答案 0 :(得分:5)

您正在创建一个类型为B的对象。根据您的类层次结构,每个B对象也是一个A,但不是一个C

现在让我们看一下如何将对此B对象的引用分配给各个变量:

Object o = new B(); // You can always assign references to an Object-typed variable.
A a = (A) o; // This works because the object is of type A.
B b = (B) o; // This works because the object is of type B.
C c = (C) o; // This does not work because the object is not of type C.

答案 1 :(得分:1)

因为理论上B可以是C,但不一定是C

B b = new C ();

投降不是一个好主意。每次投影时,最好附上一张支票。

if ( b instanceof C) {
    C c = (C) b;
}