Polymorphism In Object-Oriented Programming

Yasir Bhatti
3 min readNov 3, 2019

--

The word ‘Polymorphism’ literally means occuring in different forms or shapes. Similarly in the Object-Oriented Programming paradigm, Polymorphism can be achieved in multiple ways.One object of different classes can be accessed through same interface or one methods can have multiple implementations for one object. Polymorphism is one of the core concepts of Object-Oriented Programming and an even important one.Let us dive into its uses,types,working and importance a bit more clearly.

Types Of Polymorphism

There are two types of polymorphism in OOP .First is Compile-Time Polymorphism .Second is Run-Time Polymorphism(a.k.a Dynamic Method Dispatch).

1.Compile-Time Polymorphism :

This type of polymorphism is achieved by making multiple methods of the same signature(method name,return type,modifiers) in the same class but,with different parameters.The parameters can be different in either number or datatype.This procedure is called Method Overloading(Example Given In Image Below).

Compile-Time Polymorphism using Method Overloading.

OUTPUT : 11 ,12.75 ,12.306

1.Run-Time Polymorphism :

The way of achieving run-time polymorphism is through Method Overriding in which multiple methods are created with the same signature and differing in parameters but existing in different classes .This type of polymorphism is also known as Dynamic Method Dispatch.There are two ways to achieve Dynamic Method Dispatch using Overriding i.e 1.By using a parent class’s reference to create a child class’s object and call to overriden method OR 2.By using reference of an interface to create a class’s object to call an overriden method .The reason that this type of polymorphism is called Run-Time Polymorphism is because the compiler decides at run-time as to which method to call and from which class.

1.Using Parent’s Class Reference :

In this way,a class is created and methods are created in it and then other classes are created which inherit it.The methods are overriden in the child class and later called as required.An example is given in the image below.

Overriding Example

2.Using an Interface’s Reference:

This type of run-time polymorphism is rarely ever used in common programs.It is used when we are working with Design Patterns ,which are generally used by software houses and enterprises to develop big projects.

It is achieved by creating an interface with methods and implementing the interface to classes.Then the methods are called with the interface’s reference but object of the class whose method you want to call.

‘’The importance of polymorphism is another article long topic in itself but to summarize it,Polymorphism helps programmers to reuse the code of the methods and classes and helps in reducing coupling between multiple different functionalities’’.

--

--