[英]java casting ClassCastException
I have the following classes:我有以下课程:
public abstract class A implements C {
...
}
public abstract class B extends A {
method();
}
But when I try to do the following但是当我尝试执行以下操作时
A a = null;
A a = new A();
((B) a).method();
I receive a ClassCastException, does anyone have a solution?我收到 ClassCastException,有人有解决方案吗?
B extends A, but A doesnt extend B. B 扩展 A,但 A 不扩展 B。
everything A has B has, but A cant do the stuff declared in B A 有 B 的所有东西,但 A 不能做 B 中声明的东西
An instance of B
is an instance of A
, but an instance of A
is not necessarily a B
.的一个实例
B
是实例A
,但实例A
不一定是B
。 Similar to saying "all circles are shapes, but not all shapes are circles".类似于说“所有圆都是形状,但并非所有形状都是圆”。
You can't do what you are trying to do.你不能做你想做的事。 That's why you get the exception.
这就是为什么你会得到例外。
I think what you want here is a constructor to take and A object and make a larger B object out of it which has the included method (which A does not have).我认为您在这里想要的是一个构造函数来获取 A 对象并从中创建一个更大的 B 对象,该对象具有包含的方法(A 没有)。 But that doesn't make a whole lot of sense.
但这并没有多大意义。 Cant think for the life of me why you would want to do this in practice, and wouldn't just build the B object to start with.
我一辈子都想不通你为什么要在实践中这样做,而不是一开始就构建 B 对象。
public abstract class A implements C {
...
}
public abstract class B extends A {
public B(A child){
//Construct a B out of A here
}
public void method();
}
Then然后
A a = null;
A a = new A();
new B(a).method();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.