Java中允许向上转换,但是向下转换会产生编译错误.
可以通过添加强制转换来删除编译错误,但无论如何都会在运行时中断.
在这种情况下,为什么Java允许向下转换,如果它不能在运行时执行?
这个概念有什么实际用途吗?
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");
}
}
Run Code Online (Sandbox Code Playgroud)