Flipped Coding

What is polymorphism?

learn more about What is polymorphism?
This is another one of those obscure terms that developers tend to use a lot. Similar to inheritance, it’s one of those concepts that is both easy to understand but hard to explain concisely.

If you’ve been trying to find a definition of polymorphism that makes sense, I hope that this will help you.

In a nut shell, polymorphism means that you can use the same interface for different underlying data types. A simple example of polymorphism in action is basic math. You can add an integer and a float together and you won’t have any problems due to the mismatched data types.

The most notable way you’ll probably see polymorphism is in classes. This concept ties back into inheritance because you are dealing with derived classes that can overwrite the superclass’s properties and methods. When a derived class has overwritten a superclass method or property, then the code will refer to the derived class for that method or property.

Here’s a graphic of what that looks like:

diagram of how polymorphism works

In this case, Dinner is the super class and Thai, Italian, and Peruvian are derived classes. As you can see, each Recipe method in the derived classes are different. So for example, when you declare an object using the Dinner class and you make a new instance of a Peruvian object, you can use the Recipe() method and not worry about what code will be executed. It will automatically defer to the code for the Recipe() method defined in the Peruvian class.

That’s what polymorphism is. A method from a derived class can overwrite the method for a super class. So you can define an object with a super class and then instantiate it with a derived class. Then when you access the method, the correct code block will run every time.

I hope you were able to understand what polymorphism is!

Hey! You should follow me on Twitter because reasons: https://twitter.com/FlippedCoding