DEV Community

Milecia
Milecia

Posted on • Updated on

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:

graphical representation of polymorphism

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.


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

Top comments (2)

Collapse
 
flippedcoding profile image
Milecia

Thanks Nick! I'm glad it made sense to you.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.