ClassCastException

后端 未结 4 1855
野趣味
野趣味 2020-12-21 00:12

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;

 pub         


        
4条回答
  •  生来不讨喜
    2020-12-21 00:50

    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.

    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.

提交回复
热议问题