Author Profile Altaf Shaikh
Altaf Shaikh

BE Engg | Python Dev | Content Writer | Founder of TeachMeBro | Blockchain Dev | Django

Polymorphism in OOPs

October 15th 2020   37

Polymorphism in OOPs
Polymorphism in OOPs

Polymorphism:

Polymorphism refers to the ability of a variable, object or function to take on multiple forms. Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means forms.  For example, in English, the verb run has a different meaning if you use it with a laptop, a foot race, and business. Here, we understand the meaning of run based on the other words used along with it.The same is also applied to Polymorphism. In other words, polymorphism allows you to define one interface or method and have multiple implementations.

polymorphism example

 

Polymorphism in Java is of two types: 

  • Runtime polymorphism:

It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding.

  • Method Overriding

If subclass (child class) has the same method as declared in the parent class.

Method Overriding code example

 

#Note: Static method cannot be overridden. It is because the static method is bound with class whereas instance method is bound with an object. Static belongs to the class area, and an instance belongs to the heap area. That is why, java's main method cannot be overridden as it is also a static method.

 

  • Compile time polymorphism

In Java, compile time polymorphism refers to a process in which a call to an overloaded method is resolved at compile time rather than at run time. It is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading.

  • Method overloading:

Method overloading with example code