简体   繁体   English

java铸造ClassCastException

[英]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.

相关问题 Java多态性转换-运行时错误ClassCastException - Java polymorphism casting - runtime error ClassCastException 接口期间的java classcastexception和一些类的转换 - java classcastexception during interface and some class casting 转换为同一类时出现java.lang.ClassCastException-ClassLoader问题 - java.lang.ClassCastException when casting to the same class - ClassLoader issues 在Java中转换为泛型类型不会引发ClassCastException? - Casting to generic type in Java doesn't raise ClassCastException? Java中将Object []数组转换为泛型类型数组时发生ClassCastException - ClassCastException when casting Object[] array to generic type array in Java 在加载程序之间进行转换时如何修复 ClassCastException? Java RMI - How to fix ClassCastException when casting between loaders? Java RMI java.lang.ClassCastException:android.app.Application - cast - java.lang.ClassCastException: android.app.Application - casting 对泛型参数类型的错误转换不会在Java中引发ClassCastException - A bad casting to Generics parameter type does not throw ClassCastException in Java java.lang.ClassCastException:将对象强制转换为其父对象 - java.lang.ClassCastException: casting an object, to his parent 将 java.lang.Object 转换为自定义 object 会引发 ClassCastException - Casting java.lang.Object to custom object raises ClassCastException
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM