I was once asked in an interview, “Can you tell me what polymorphism is?”
A straightforward enough question. Or is it? This can be exactly the kind of question that catches you off guard. You’ve used objects for years and of course you know what polymorphism is. But can you explain it in a concise and intelligent manner? This 5 minute guide to polymorphism will lay it all out clearly, so next time someone asks you, you can say, “Yes, let me explain it to you.”
The word is greek in origin and translates literally to ‘many’ + ‘forms’.
Polymorphism is a descriptive term used in sciences such as biology and chemistry, but it has also been adopted by the object oriented programming methodology.
In a single sentence, polymorphism describes the ability of different objects to be accessed by a common interface.
What does that mean though?
At its most basic, an object is polymorphic if it is related to one or more other objects that can ALL be utilized using the same methods.
To illustrate this with a trivial (and very non-scientific) example, consider the following.
In a room stands a mouse, a cat and a dog. From the far corner of the room, a speaker emits the sudden sound of a balloon popping. The mouse, the cat and the dog all immediately turn toward the direction of the sound. The dog barks, the cat twitches its tail and the mouse sniffs the air.
Programmatically, we can summarize this bizarre scenario as follows:
The mouse, cat and dog are 3 unique objects. They are not the same, but they have some characteristics that are the same. Together, they descend from a more generic superclass, which we will call a mammal. Mammals have ears, which allow them to process sound. The sound of the balloon popping causes each ‘object’ to process the sound in its own way: barking, tail-twitching and sniffing.
These ‘objects’ are polymorphic. Why?
Because although they all behave in different ways, the same method can be used to interact with them, and that method derives from a superclass. And thus here is the crux of the whole thing:
You don’t need to know which type of object you are talking to in order to utilize the method to talk to it.
Polymorphism allows you to talk to an object, without knowing exactly what the object is. If an object is polymorphic, it could be one of many different forms defined by you, the programmer, and descended from a generic base class. All you need to know is what generic type you are talking to and the available methods to talk to it.
Once you’ve called upon the method, the polymorphic type of the object will determine exactly how it behaves in response.
So there you have it. Polymorphism in a nutshell 🙂
I’ve written up the example above in C++ code, so if you want to see it in action, with the actual nuts and bolts of declaring and using objects polymorphically, you can find that here.