As discussed in Java Class Inheritance, since every sub-class object is also a super-class object, we can assign a sub-class object to a super-class reference. This is also called as downcasting. e.g., the object of type Drama can be assigned to the reference of the type Entertainment.
Entertainment e; Entertainment reference, and also created a Movie reference and object. At LINE A , we have assigned the Movie reference m to the Entertainment reference e . Similarly, we have created a Drama reference and object and assigned the same to the Entertainment reference e .
The assignment at LINE C will not work, since we are assigning a reference of type Drama to a reference of type Movie . Since Drama is not a Movie (i.e. the type of Drama and Movie are different), the assignment causes a compilation error.
Look at Assigning Super Class Reference To A Sub Class Reference In Java which explains how the references of super-class type can be assigned to a sub-class reference.
|