以下程序:
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?

解决方案 »

  1.   

    Father is Father...Son is Son...Son can be a father...Father can not be a son...class Father{
    }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!
       }
    }
      

  2.   

    因为A不是B类型,也不是B的子类型.
      

  3.   

      如果父类对象的引用指向的实际是一个子类的对象,那么父类对象的引用可以强制转化成子类对象的引用。
    把  A x = new A(); 改成 A x = new B(); 是可以的