What is Polymorphism?

Inheritance goes hand-in-hand with Polymorphism (an important concept in object-oriented programming wherein objects function interchangeably). In Polymorphism a class inherits from a parent class and gains the ability to function as its parent in places where the parent class would have been required. Due to this type interchangeability, your code becomes more fluid because it allows you to write general logic to handle multiple classes/types instead of specific logic for each.

For example, if you had an “Animal” class and a “Dog” class that inherits from the animal class, your Dog class could be used anywhere an animal class is expected. The same is true of any other classes you might have created that inherit from the “Animal” class.

Without Inheritance, Polymorphism falls apart. In short, Inheritance allows you to create a hierarchy of classes and Polymorphism is the practice of making use of the hierarchy to minimize rework.

When would you use it?

You’d use Polymorphism anytime you’re developing in an object oriented language and would like to avoid rework.

Why is it valuable?

Polymorphism is valuable because it saves time and makes programming easier. If you understand the concept then it makes it easier to write and read code in object-oriented languages. A practical example would be if you need to understand the behavior of an object/class in one part of your code. To figure out this mystery behavior you could trace the classes hierarchy/parents until the behavior makes sense.

However, if you don’t understand the concept and are working in an object-oriented language then you’re making use of it in some places a completely ignoring it in others.