top of page
Search

Object Oriented Programming (OOP) Core Principle: Polymorphism

Polymorphism, as the name suggests, has something to do with many (poly) and to change/to form (morph). Let’s see what it means in the OOP world.


Polymorphism

The WHAT

I like to think about polymorphism as the ability of an object to behave differently based on their data type.

Let’s take an example to make it easier to understand.

Imagine a rock band having 4 members: a drummer, a lead guitarist, a bassist and the singer. Let’s focus on the members:

  1. a drummer plays drums (d’oh) and produces the sound by hitting them with the two sticks in both hands and pressing pedals with the feet

  2. a lead guitarist plays the guitar and produces the sound by fretting one or more notes on the fretboard with one hand and hitting one or more of the 6 strings with the other hand

  3. a bassist plays the bass guitar and produces the sound by fretting one or more notes on the fretboard with one hand and hitting one or more of the 4 strings with the other hand. The bass sound is much deeper compared to the guitar

  4. the singer “plays” with his/her vocal cords and produces the sound using his/her voice

Now, assume you go to this band and tell them: Please play song X. Assuming they know it, they will start to play it. But something interesting is happening. Even though you said “play song X“, this means very different things for every member: for the drummer there are specific sounds which are generated in a specific way (hitting drums with sticks and pedals). The same goes for the guitarist, bassist and singer. Different behavior of “play song x” depending on the role (guitarist, bassist, drummer, singer) in the band. This is polymorphism.

Here are a few other classic examples of polymorphism: * shapes: you have different shapes – triangle, square, rectangle, circle etc. For each shape there is a specific formula for calculating the area of the shape. You can have a method called GetArea() implemented differently for each of the shape classes (Triangle, Square, Rectangle, Circle) to properly calculate the area of that shape * vehicles: you have different vehiclesbicycle, motorbike, car, boat. For each vehicle there is a specific way to make it Move() * living organisms: human, cat, butterfly, fish. Same idea as for vehicles, there is a specific way a living organism to Move()

The HOW

I hope by now you have a better understanding of polymorphism. Let’s talk a bit about how you can achieve it. There are two types of polymorphism:

  1. static

  2. dynamic

Static polymorphism happens at compile-time (before execution, when you compile your code). This type of polymorphism is also known as Compile-Time polymorphism or Static binding or Compile-Time binding or Early binding or Method overloading. Fancy words for something very simple – method overloading.

The most simple example here is an Add(int a, int b) method. By using method overloading, we can create another method of the object, Add(int a, int b, int c) so that we can now add three numbers instead of two using the same Add() method called with different parameters (also known as method signature). This is it.

Dynamic polymorphism happens at run-time (after compilation, when your code is executing). This type of polymorphism is also known as Run-Time polymorphism or Dynamic binding or Run-Time binding or Late binding or Method overriding. Another mouthful of fancy words for something yet again simple – method overriding.

In the band example from above, you would have a base class Musician with a Play() method. Guitarist, Bassist, Singer, Drummer would be derived classes from Musician, each having its own implementation of the Play() method.

In C# for example, the method Play() from Musician needs to be marked as virtual or abstract. The same method, Play(), from Guitarist, Bassist, Singer, Drummer needs to be marked with override for the polymorphism to be applied.

Another popular form of dynamic polymorphism is through the use of interfaces. Having the same band example as above, you would have an interface, IMusician, instead of a basic class. This interface would have the Play() method which will need to be implemented in Guitarist, Bassist, Singer, Drummer as these classes will all implement the IMusician interface.

The WHY

I hope you get the concept, and by now you should ask yourself, why would you ever use this?

In practice, you will want to keep your code as generic as possible. There might be cases where you need to work with several specific objects, but you don’t have access to those object yet, but you do know they will implement an interface. In this case, you can write your code in a simple, generic way, as you will rely on the interface (or base class if available). Since you don’t need to have dedicated (duplicated) code to handle all the objects which implement that interface in a separate way, polymorphism will simplify your code and make your life easier. Think about writing an application which needs to perform a search query on three different search engines (Google, Bing, Yahoo) and return the top result. In your code, you don’t care how the query is performed behind the scenes in each search engine object and how the results are returned. If you know all these future objects implement the ISearchEngine interface which has the GetFirst(string keywords) method, you can build your application based on this interface before having access to the specific objects. Your code will not require any changes after you get access to the actual objects (Google, Bing, Yahoo).

Another similar case is where you have access to all objects, but again, you don’t want to treat them differently, you just need to execute a specific method and get the output (or not). Using the search engine example, your code will not need to treat the objects (Google, Bing, Yahoo) in a different manner in order to get the results, GetFirst(string keywords) will work in a consistent way across all objects.

Conclusion

Polymorphism might seem intimidating at a first glance, but it is not that hard as a concept. In order to see its value you need some hands on experience.

In your favourite programming language, take the above examples and try to implement them without polymorphism and see how your code looks like. Then, do the same thing by applying polymorphism and your code should simplify.

If you need any feedback on your polymorphed code or you have questions, contact me via Facebook or drop me a line, I’ll follow up on it, I promise.

Comments


bottom of page