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

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

    I'm not sure about the compile part, but I can explain the runtime error.

    B extends A, which means that every object of class B, is also an object of type A. The other way around is not true.

    Compare A with 'Mammal', and B with 'Cow'. A Cow is always a Mammal, but not every Mammal is a Cow.

提交回复
热议问题