以下程序:
class A {
}class B extends A {
}class C extends A {
}public class Test { public static void main(String args[]) { A x = new A(); B y = new B(); C z = new C();
y = (B)x;
}
}编译通过,运行时却出现错误:
Exception in thread "main" java.lang.ClassCastException: A cannot be cast to B
at Test.main(Test.java:20)为什么A cannot be cast to B?
class A {
}class B extends A {
}class C extends A {
}public class Test { public static void main(String args[]) { A x = new A(); B y = new B(); C z = new C();
y = (B)x;
}
}编译通过,运行时却出现错误:
Exception in thread "main" java.lang.ClassCastException: A cannot be cast to B
at Test.main(Test.java:20)为什么A cannot be cast to B?
}class Son extends Father{
}public class Test{ public static void main(String args[]){
Father f = new Father();
Son s = new Son(); f = (Father)s; //This is OK!
s = (Son)f; //This is wrong!
}
}
把 A x = new A(); 改成 A x = new B(); 是可以的