Java 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:

  1. Compile time polymorphism: This is also called as static polymorphism or method overloading.
  2. Runtime polymorphism: The is also called as dynamic polymorphism or method overriding.

Runtime polymorphism (function overriding)

Dynamic polymorphism or function overriding also called runtime polymorphism.

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:

  1. Method name must be same in both parent and child class.
  2. Method should have same number and sequence of parameter.
  3. There must be an IS-A relationship (inheritance).

Example:

OUTPUT:

This is Audi car engine

Compile time polymorphism (function overloading):

Compile time polymorphism 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:

  1. 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

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan