In java:
Base b = new Base();
Derived d = (Derived)b;
throws ClassCastException
. Why? Why downcasting throws Exception<
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