This big word is not as scary as it may seem, but it is one of the fundamentals of OO coding which can not be overlooked. Polymorphism is one of those areas which seem more difficult than it is. Ivar Jacobson, one of the fathers of use cases and an OO heavyweight describes polymorphism as -

Polymorphism means that the sender of a stimulus does not need to know the receiving instance's class. The receiving instance can belong to an arbitrary class.

So what does that mean? It means that a object which is talking to another object does not need to know what class it is. So a instance of class A can talk to another instance without knowing what class it is. But how can this be? If we write some code which is using a object, surely we need to know what class it is. If we wanted to add a element to a stack, we need to talk to a stack object surely? So is polymorphism just a bizarre idea which is simply impractical?

The short answer is no. Ivar Jacobson is being a little ambitious when he says any arbitrary class. In terms of java, he means any arbitrary class which belongs to the same object hierarchy.

Consider this example. We have a class which receives requests to work out employee pay slips and employee records. These requests can come in any order and at any time. A first stab at this class may look like this.

So whatever sends these requests must use the correct method. Pay slips go to the pay slip method and so on. However this is not a very good solution as it means that we must always know which one we are working on. If you remember, both of these classes inherit from TaxCalculator. As such we can let class Controller use polymorphism. Here is the improved version.

This class is exhibiting polymorphic behaviour. That is, it is using polymorphism. So how does it work? Let’s say the first request is for a pay slip. The method ProcessTax is called on an instance of Controller.

// creates a instance of Controller

Controller control = new Controller();

// the tax request, a payslip

Payslip request = new Payslip();

// uses polymorphism to work out tax

Control.processTax(request);

 

Notice that the instance request is of class Payslip. This is passed to the method ProcessTax which is expecting a TaxCalculator instance. If Payslip did not inherit from TaxCalculator then the code would fail to compile. Because it does inherit and is part of its object hierarchy it is allowed. Process tax can then call the inherited method calculateTax on the request instance. Effectively the Controller instance does not know, nor does it care, what class it acts upon as long as it is a subclass of TaxCalculator. This is known as polymorphism.