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

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

    It's simple. Think that when you are extending you have to use is a

    B `is a` A
    A `is not` B
    

    A more realistic example

    class Animal{
    }
    
    class Dog extends Animal{
    }
    
    class Cat extends Animal{
    }
    

    A DOG IS A Animal AN ANIMAL IS NOT a DOG necessary (Example : a cat is not a dog, and a cat is an animal)

    You are getting runtime exception cause , in runtime realize that that animal is not a dog, this is call downcasting and is not safe what are you trying to do.

    0 讨论(0)
提交回复
热议问题