java.lang.ClassException: A cannot be cast into B

后端 未结 13 1172
南笙
南笙 2020-12-31 09:05

I implemented this code:

class A {
    //some code
}
class B extends A {
    // some code
}

class C {
    public static void main(String []args)
    {
              


        
13条回答
  •  执笔经年
    2020-12-31 09:20

    The reason it fails at runtime is that the object isn't a B. It's an A. So while some As can be casts as Bs, yours cannot.

    The compilier just can't analyze everything that happened to your A object. For example.

    A a1 = new B();
    A a2 = new A();
    
    B b1 = (B) a1;    // Ok
    B b2 = (B) a2;    // Fails
    

    So the compilier isn't sure whether your A object is actually castable to a B. So in the above, it would think that the last 2 lines were ok. But when you actually run the program, it realizes that a2 is not a B, it's only an A.

提交回复
热议问题