类转换异常
我在java中有两个类:
class A {
int a=10;
public void sayhello() {
System.out.println("class A");
}
}
class B extends A {
int a=20;
public void sayhello() {
System.out.println("class B");
}
}
public class HelloWorld {
public static void main(String[] args) throws IOException {
B b = (B) new A();
System.out.println(b.a);
}
}
在编译时它不会给出错误,但在运行时它显示一个错误: 线程“main”中的异常 java.lang.ClassCastException:A 无法转换为 B
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
发生这种情况是因为
new A()
的编译时表达式类型是A
- 它可能是一个引用到B
的实例,因此允许强制转换。然而,在执行时,引用只是对 A 实例的引用,因此转换失败。
A
的实例不是B
的实例。仅当引用确实引用B
或子类的实例时,强制转换才有效。This happens because the compile-time expression type of
new A()
isA
- which could be a reference to an instance ofB
, so the cast is allowed.At execution time, however, the reference is just to an instance of
A
- so it fails the cast. An instance of justA
isn't an instance ofB
. The cast only works if the reference really does refer to an instance ofB
or a subclass.B 扩展了 A,因此 B 可以转换为 A。但反之则不然。 A 的实例不能转换为 B。
如果您来自 Javascript 世界,您可能会期望它能够工作,但 Java 没有“鸭子打字”。
B extends A and therefore B can be cast as A. However the reverse is not true. An instance of A cannot be cast as B.
If you are coming from the Javascript world you may be expecting this to work, but Java does not have "duck typing".
首先这样做:
现在进行显式转换,它将起作用:
这意味着显式转换必须需要隐式转换。否则不允许显式转换。
First do it like this :
Now do your Explicit casting, it will work:
That mean's Explicit casting must need implicit casting. elsewise Explicit casting is not allowed.
一旦创建了子类的对象,就无法将其类型转换为超类。只需查看以下示例
假设:
Dog 是继承自 Animal(SuperClass) 的子类
正常类型转换:
错误类型转换:
下面的类型转换确实有效:
编译器检查语法它是在运行时内容被实际验证的
Once you create the object of a child class you cannot typecast it into a superClass. Just look into the below examples
Assumptions:
Dog is the child class which inherits from Animal(SuperClass)
Normal Typecast:
Wrong Typecast:
The below Typecast really works:
A compiler checks the syntax it's during the run time contents are actually verified