ClassCastException [英] ClassCastException
问题描述
我在Java中有两个类:
i have two classes in java as:
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
at compile time it does not give error, but at runtime it displays an error : Exception in thread "main" java.lang.ClassCastException: A cannot be cast to B
推荐答案
这是因为 new A()
的编译时表达式类型为 A
- 其中可以是对 B
的实例的引用,因此允许转换。
This happens because the compile-time expression type of new A()
is A
- which could be a reference to an instance of B
, so the cast is allowed.
但是,在执行时,引用只是一个 A
的实例,所以它不能转换。 A
的实例不是 B
的实例。如果引用确实指向 B
或子类的实例,则强制转换仅适用。
At execution time, however, the reference is just to an instance of A
- so it fails the cast. An instance of just A
isn't an instance of B
. The cast only works if the reference really does refer to an instance of B
or a subclass.
这篇关于ClassCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!