Polymorphism
Polymorphism is one of the four pillars of OOP concepts in Java. Polymorphism is a concept where we can perform single action in different ways.
For Example, We have a generic Car class with engine() as one of the generic method as shown below. This generic method will get actual definition in the child class function.
In programming language term: The engine() function will perform different actions depending on which object is calling.
Types of polymorphism:
- Compile time polymorphism: This is also called as static polymorphism or method overloading.
- Runtime polymorphism: The is also called as dynamic polymorphism or method overriding.
Runtime polymorphism (function overriding):
This is also called as dynamic polymorphism or function overriding.
Function having same name with exactly same number and sequence of parameters defined in both parent and child class is called as function overriding.
Process where call to overridden method will get resolves only at dynamic or run time.
Function overriding Rules:
- Method name must be same in both parent and child class.
- Method should have same number and sequence of parameter.
- There must be an IS-A relationship (inheritance).
Example:
OUTPUT:
This is Audi car engine
Compile time polymorphism (function overloading):
This is also called as static polymorphism or function overloading. Process where call to overload method will get resolves only at compile time.
Function having same name, but different number and type of parameters are called as function overloading.
Function Overloading Rules:
- By changing number of parameters.
If we must perform addition of different numbers will lead us to create overloaded function.
Below are the examples of add function overloading with different parameter:
2. By changing data type in the parameters.
Below is the example for addition of two int and float variables:
Example:
OUTPUT:
2
3
6
In the above example, the add method got overloaded three time with different method parameters in the Calculator class. First add method has only 1 parameter, second add method has 2 parameters, third add method has 3 parameters. Which add() method will get call will totally depend on the number of parameter passed while calling function.
Note:
Method Overloading can happen in same class as well as in parent child class relationship.
Method overriding can happen only in an inheritance which is parent child relationship.
Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.