最佳答案
在Java中允许向上强制转换,但是向下强制转换会产生编译错误。
可以通过添加强制转换来删除编译错误,但无论如何都会在运行时中断。
在这种情况下,为什么Java允许向下强制转换,如果它不能在运行时执行?< br > 这个概念有什么实际用途吗?< / p >public class demo {
public static void main(String a[]) {
B b = (B) new A(); // compiles with the cast,
// but runtime exception - java.lang.ClassCastException
}
}
class A {
public void draw() {
System.out.println("1");
}
public void draw1() {
System.out.println("2");
}
}
class B extends A {
public void draw() {
System.out.println("3");
}
public void draw2() {
System.out.println("4");
}
}