Jul 162011

Reference variables may be cast between different types. Casting from a subtype to a supertype is referred to as upcasting and is an inherently safe operation. Casting from a supertype to a subtype is referred to as downcasting and is an inherently unsafe (but often necessary) operation that requires an explicit type cast.

Consider the following UML class diagram:

As you can see, Employee is the superclass of Accountant and Mechanic. The two subclasses define specialized roles, and the superclass a more general role. Any type of employee (Employee, Accountant, and Mechanic) can getId and complain, but only an Accountant can doPayroll.

Employee e1 = new Accountant();
Employee e2 = new Mechanic();
Employee e3 = new Employee();

e1.complain("They stopped my $10,000 bonus.");
e2.complain("The kettle is broken.");
e3.complain("Life sucks!");

Now consider what would happen if we instantiated an Accountant object and later assigned this to an Employee reference variable. This would be an inherently safe operation as this would restrict the capabilities of the new variable.

Accountant a1 = new Accountant();
// do some interesting stuff...
// and later...
Employee e4 = a1; // safe operation - implicit upcasting

On the other hand, casting from an Employee to an Accountant or Mechanic object type would be an inherently unsafe operation that requires an explicit type cast. Nevertheless, we might need to do this to access specialized methods of the subclass.

Employee e5 = new Accountant();
// do some general stuff...
e5.complain("My desk isn't big enough.");
// and later...
Accountant a2 = (Accountant) e5; // requires explicit cast

However, downcasting to the wrong type would cause an exception. For example,

Employee a = new Accountant();
Mechanic m = (Mechanic) a; // java.lang.ClassCastException
m.fixCar(new Car());

Hopefully, that all makes sense!

  One Response to “Upcasting and downcasting Java reference variables”

  1. [...] on from my earlier post about upcasting and downcasting, I thought I’d post another example to show how downcasting can result in an [...]

 Leave a Reply



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>