Why Downcasting throws Exception?

前端 未结 4 1036
囚心锁ツ
囚心锁ツ 2021-01-19 05:18

In java:

Base b = new Base();
Derived d = (Derived)b; 

throws ClassCastException. Why? Why downcasting throws Exception<

4条回答
  •  囚心锁ツ
    2021-01-19 05:24

    Let me rename your classes to make things more clear. Base -> Animal. Derived -> Cat.

    Just because you're an Animal doesn't mean you're a Cat. You could be a Dog. That's why it's illegal to cast an Animal into a Cat.

    On the other hand, is every Cat an Animal? The answer is "yes". That's why you could write code like this:

    Animal animal = new Cat();
    

    or

    Cat cat = new Cat();
    Animal animal = cat;
    

    Also what's worth noting is you can do this:

    Animal animal = new Cat();
    Cat cat = (Cat) animal;
    

    The reason you can do this is that your animal variable is actually referencing a Cat instance. Therefore you're allowed to cast it back into a variable that references a Cat.

提交回复
热议问题