Topics Index

Class Inheritance >
Siva Nookala - 12 Apr 2016
As discussed in Is-A Relationship In Java every sub-class object is also of type super-class. Although all of the super-class objects are not of the sub-class type, some of them are. So the super-class references can be assigned to sub-class reference, if we know that the super-class reference is holding an object of sub-class type.

Entertainment ent1;
Drama d1 = new Drama();
ent1 = d1;

Drama d2 = (Drama) ent1; // LINE A
As shown here, we are first creating a reference of Entertainment called ent1, a reference of Drama called d1 and a Drama object. Since we know that ent1 is referring to an object of type Drama, we can up cast the reference as shown in LINE A and assign it to another Drama reference d2.
Instead, if we try to up cast a reference which does not refer to the correct object type, then it throws a ClassCastException during run time.
Entertainment ent1;
Circus c1 = new Circus();
ent1 = c1;

Drama d2 = (Drama) ent1; // LINE A - THROWS ClassCastException
Circus c2 = (Circus) ent1; // LINE B - WILL WORK
Here a ClassCastException is thrown at LINE A, since ent1 points to Circus object and hence can not be cast to a Drama. But the casting as done in LINE B will work since ent1 points to the Circus object.

Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.