Types of Polymorphism
Polymorphism means that a operation can also be applied to values of some other types.
There are multiple types of Polymorphism:
- Ad hoc polymorphism:
function overloading. The target is that a Method can be used with different types without the need of being generic.
- Parametric polymorphism:
is the use of generic types. See Generics
has the target inherit of a class to generalize a similar functionality
Ad hoc polymorphism
The target of
Ad hoc polymorphism is to create a method, that can be called by different datatypes without a need of type-conversion in the function call or generics. The following method(s)
sumInt(par1, par2) can be called with different datatypes and has for each combination of types a own implementation:
Here's a example call:
Subtyping is the use of inherit from a base class to generalize a similar behavior:
ElectricCar now have a method to refuel, but their own implementation. Here's a Example:
The output will be was following:
Refueling with petrol
Another Polymorphism Example
Polymorphism is one of the pillar of OOP. Poly derives from a Greek term which means 'multiple forms'.
Below is an example which exhibits Polymorphism. The class
Vehicle takes multiple forms as a base class.
The Derived classes
Lamborghini inherits from
Vehicle and overrides the base class's
Display() method, to display its own
Below is the code snippet where Polymorphism is exhibited. The object is created for the base type
Vehicle using a variable
vehicle at Line 1. It calls the base class method
Display() at Line 2 and display the output as shown.
At Line 3, the
vehicle object is pointed to the derived class
Ducati and calls its
Display() method, which displays the output as shown. Here comes the polymorphic behavior, even though the object
vehicle is of type
Vehicle, it calls the derived class method
Display() as the type
Ducati overrides the base class
Display() method, since the
vehicle object is pointed towards
The same explanation is applicable when it invokes the
The Output is shown below