3.5.5 How to Upcast an Object

Upcasting "transforms" or "morphs" an object into a more general type. This is done to limit the functionality of the object. When something is upcasted it strips the object of members that may not be applicable to the situation.

We have an Employee class that has a child class of Attendant.

We can't instantiate the Employee class so we have to instantiate an Attendant.

That attendant object has all of the members that the Attendant class has.

But what if we don't want the object to do stuff that an Attendant does? What if we only want it to do things an Employee does? We can cast the Attendant object as an Employee type and strip the object of its Attendant members. This makes the object change from a specific to a generic type.


The Attendant type can be thought of as a complicated, multi-faceted object as shown below. There are methods that are both in the Attendant class and the Employee class that it has.

Once we cast it to a more generic type, however, the members that relate to the Attendant class are no longer there and the object becomes a little less complicated and more generic.

It is called "upcasting" because we are moving "up" the hierarchy.

In code, this looks like: