Menu
Topics Index
...
`


Class Inheritance >
Siva Nookala - 12 Apr 2016
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;

Movie m = new Movie();
e = m; // LINE A

Drama d = new Drama();
e = d; // LINE B

m = d; // LINE C - WON'T WORK, SINCE A DRAMA OBJECT IS NOT OF TYPE MOVIE.
Here we created an 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.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.