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

后端 未结 13 960
南笙
南笙 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:13

    Following is a compiletime casting -

    A a = new B();
    

    Such static castings are implicitly performed by the compiler, because the compiler is aware of the fact that B is-a A.

    Following doesn't compile -

    B b = new A();
    

    No compiletime casting here because the compiler knows that A is not B.

    Following compiles -

    B b = (B) new A();
    

    It is a dynamic casting. With (B) you are telling the compiler explicitly that you want the casting to happen at runtime. And you get a CCE at runtime, when the runtime tries to perform the cast but finds out that it cannot be done and throws a CCE.

    When you do (or have to do) something like this, the responsibility falls upon you (not the compiler) to make sure that a CCE doesn't occur at runtime.

提交回复
热议问题