Why Downcasting throws Exception?

前端 未结 4 1032
囚心锁ツ
囚心锁ツ 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.

    0 讨论(0)
  • 2021-01-19 05:30

    To downcast in Java and avoid run-time exceptions, take a reference of the following code:

    if (animal instanceof Cat) {
      Cat cat = (Cat) animal;
    }
    

    Here, Animal is the parent class and Cat is the child class.

    instanceof is a keyword that is used for checking if a reference variable is containing a given type of object reference or not.

    0 讨论(0)
  • 2021-01-19 05:34

    A derived class inherits the behavior from its super class. Hence, casting a sub-class object to a super-class reference works since the derived class object is capable of fulfilling the contract defined by the super-class.

    On the other hand, a super-class (by the very way you define the classes) clearly doesn't implement most of the methods present in the sub-class. Well, that's why you extended the super-class in the first place - to extend its implementation.

    So, casting a super-class object to a sub-class type is an inherently unsafe operation because the base class object cannot fulfill its sub-class' contract completely.

    0 讨论(0)
  • 2021-01-19 05:51

    You cannot cast a derived class as the base class. You may assign b as either a Base or a Derived, but you may only assign d as a Derived. Long story short, you may only assign a variable declared as Base a value that is of the same type (Base) or a derived type.

    This is okay (I'm just using new as an example, what matters is the data types):

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

    But this is not:

    Derived d = new Base();
    

    This is the way that inheritance works

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