gpt4 book ai didi

java - 尝试转换子类时出现 ClassCastException

转载 作者:行者123 更新时间:2023-12-02 17:01:59 29 4
gpt4 key购买 nike

我有这个代码:

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();

谢谢!

最佳答案

您正在创建一个 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.

关于java - 尝试转换子类时出现 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53720096/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com