Why Downcasting throws Exception?

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

提交回复
热议问题