Object-Oriented Programming has different concepts allowing developers to build logical code. One of these concepts is polymorphism. But what is polymorphism?

Polymorphism in Object Oriented Programming

Polymorphism is a feature of object-oriented programming languages that allows a specific routine to use variables of different types at different times. It is the ability of a programming language to present the same interface for several different underlying data types and different objects to respond in a unique way to the same message.

Polymorphism is one of the four important principles of object-oriented programming (OOP).

Main characteristics

Ad-hoc polymorphism

Ad-hoc polymorphism refers to the idea that a specific function can be applied to different arguments and may operate differently depending on the type of arguments to which it is applied. A basic example of a polymorphic function is the plus sign (+) operator. This operator can be used in several ways, including integer addition, floating-point addition, list concatenation, and string concatenation. When a single operator performs different functions depending on the type of argument, we say that the operator is overloaded. Suitably, ad-hoc polymorphism is also called function overloading or operator overloading.

Parametric Polymorphism (overloading for type)

Parametric polymorphism allows programmers to write generic functions that can treat values the same way regardless of their type. Put differently, a parametric function is a piece of code that treats all data the same way, regardless of its type. Parametric polymorphism is used to write generic functions that operate on data sets, regardless of the specific type of each element in the set.

In C++, parametric polymorphism is realized through templates.

Subtyping polymorphism in object-oriented programming

Let's assume a geometry hierarchy where we have defined a class called shape and derived classes called circle and rectangle. In subtyping, we define a supertype that may have several subtypes where various functions or subroutines were written to operate on the supertype and can also operate on the various subtypes.

Each subtype is a variety of the supertype that shares some, but not all of its characteristics. Subtype polymorphism allows a function that would normally operate on a shape-type object to also operate on objects that belong to any of the subtypes of shape. You can write a method that takes a shape as a parameter, but you can also apply it to circle because a circle is a subtype of a shape.