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; 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; 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.
|