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

后端 未结 13 964
南笙
南笙 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条回答
  •  -上瘾入骨i
    2020-12-31 09:20

    Because the A is a parent of B. B extends the functionality of the A but keeps the original functionality of A. So B can in fact be cast to A, but not vice versa.

    What if B added a new method, let's say newMethodInB(). If you would try to call that method through variable B on the instance A (imagine that the cast worked) what would you expect? Well, you would definitely get an error because that method does not exist in A.

提交回复
热议问题