Why Downcasting throws Exception?

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

提交回复
热议问题