Polymorphism

Polymorphism is one of the four pillars of Object Oriented Programming

Polymorphism usually involves derived classes which we won't cover in this article but which are looked at here. However, we will cover what polymorphism means and why it is useful.

It is really quite a simple notion despite the weird name. Polymorphism is a word derived from Greek which literally means "many shapes" or "many forms". And, as we will see, it is a very appropriate word for what it does.

Suppose we have two classes, dog and cat. Let us further suppose that both of these classes derive from a base class called animal.

If we look at the article on Encapsulation we will see that there we had a class called dog and it had a method called bark. We are going to change that so that both the dog and cat classes implement a method in the base class animal called speak.

The implementation in the dog class remains the same: return "woof"

In the cat class we also have a method called speak which has this implementation: return "meow"

So now we have two classes, both of them deriving from the same base class, both with a method called speak but each with its own implementation. So how do we use it?

The actual code will depend upon the language used but the principle is the same.

First we declare a new object, say pet of type animal. Then when we instantiate pet we do so as an instance of one of the derived classes.

For example, if we now say pet = new dog then our pet pet is an object of type dog and the following code pet.speak will return "woof".

Similarly if we were to create an object pet = new cat then pet.speak would return "meow".

Encapsulation is a very powerful tool which can lead to both simplification of code and a great reduction in the amount of code that needs to be written. It can also solve some programming problems that would otherwise seem insoluble except for massive amounts of unmaintainable work-arounds.