Java Polymorphism And Its Types

img
Prabu Rajendiran
Share

Polymorphism

Polymorphism, one of the core concepts of OOP (Object-Oriented Programming) refers to the ability of an object to take different forms at different stages. For example, when connected to a computer, a USB cable acts as a data cable to transfer data, and the same cable, when connected to a charger adapter, acts as a power cabel. In Java, polymorphism results in code that are more concise.

Types of Polymorphism

There are 3 main types of Polymorphism in Java.

  • Coercion
  • Overloading
  • Subtype

1. Coercion

Another operand is converted to a higher type in an operation based on the operand type. For example, when you perform an operation between long and double, there is no operator to perform an operation of two different types. Hence, the compiler converts the long to a double (implicit conversion). Similarly, you can pass a subclass object for the method which has the superclass parameter.

Example

long l=200;

double d=300.34;

double sum=l+d;

In the above statement, ‘l’ is a long type and ‘d’ is a double type. But, when you perform addition, the compiler converts long to a double, adds ‘l’ to ‘d’ and returns a double value.

2. Overloading

Overloading allows the same method or an operator to perform different actions based on the value. For example, when you use arithmetic operators such as +,-,/, etc., to perform an operation based on integer value/float value, it automatically performs the operation. Here, there is no need for a separate operator to perform any operation for the given types.

Also, we can have multiple methods with the same name, but the value type will be different for a method.

Example

Consider the below program, which is used to search employee data based on employee Id, employee name, salary, or designation.

public Employee search(int empId)

{

//code 

//return emp;

}

public Employee search(String employeeName)

{

//code 

//return emp;

}

public Employee search(double salary,String designation)

{

//code 

//return emp;

}

The above search methods take different types of parameters and return the value. Overloading is also called Static Binding.

3. Subtype

A base class type, when serves as a subclass type, is called a subtype. When a subclass object is assigned to a base class type, and when a base class type is executed, it results in subclass type. For example, consider a bank account that has the account details of the customer. In programming, it must have an Account class with subclasses like SavingsAccount, FDAccount, LoanAccount, and many more. You have method getAccountDetails(), which will display common information. The subclasses produce specific data of the same method getAccountDetails().

Example

import java.time.LocalDate;

import java.time.Month;

class Account

{

private int accountId;

private String customerName;

private double balance;

public Account(int accountId, String customerName, double balance)

{
super();

this.accountId = accountId;

this.customerName = customerName;

this.balance = balance;

}

public void getAccountDetails()

{

System.out.println(“ID : “+this.accountId);

System.out.println(“Name : “+this.customerName);

System.out.println(“Balance : “+this.balance);

System.out.println(“—————————————-“);

}

}

class SavingsAccount extends Account

{

private double interestRate;

public SavingsAccount(int accountId, String customerName, double balance,double interestRate) {

super(accountId, customerName, balance);

this.interestRate=interestRate;

}

public void getAccountDetails()

{

super.getAccountDetails();

System.out.println(“Interest : “+this.interestRate);

}

}

class FDAccount extends Account

{

private double interestRate;

private LocalDate maturityDate;

public FDAccount(int accountId, String customerName, double balance,double interestRate,LocalDate maturityDate) {

super(accountId, customerName, balance);

this.interestRate=interestRate;

this.maturityDate=maturityDate;

}

public void getAccountDetails()

{

super.getAccountDetails();

System.out.println(“Interest : “+this.interestRate);

System.out.println(“Maturity Date: “+this.maturityDate);

}
}

public class TestAccount {

public static void displayAccountDetails(Account account)

{

account.getAccountDetails();

}
public static void main(String[] args) {

// TODO Auto-generated method stub

displayAccountDetails(new Account(101,”Krithick”,5000));

displayAccountDetails(new SavingsAccount(201,”Chandrav”, 10000,4));

displayAccountDetails(new FDAccount(103,”Rajan”,25000, 6.25,

LocalDate.of(2021,Month.JUNE, 12)));

}
}

In the above example, the Account class has two subclasses – SavingsAccount and FDAccount, and the getAccountDetails() method needs to provide additional information, such as interest rate and maturity date. Hence the method is overridden in the subclasses.

The method displayAccountDetails() takes Account as a parameter and calls the getAccountDetails() method based on the type of object passed to the method.

Sample output

ID: 101

Name: Krithick

Balance: 5000.0

—————————————-

ID: 201

Name: Chandrav

Balance: 10000.0

—————————————-

Interest: 4.0

ID: 103

Name: Rajan

Balance: 25000.0

—————————————-

Interest: 6.25

Maturity: 2021-06-12

Important features of Polymorphism in Java:

  • The efficacy of a method operates differently in different contexts.
  • The behavior of a method is determined by the data presented.
  • It enables the use of the same name for a member or method in a class with various kinds.
  • Polymorphism allows implicit type conversion.

Compile Time Polymorphism vs. Runtime Polymorphism

Compile Time Polymorphism

Runtime Polymorphism

  • Method calls in run-time is handled by the compiler
  • Method calls in run-time is not handled by the compiler
  • It is less flexible, as it requires handling all method calls
  • Exhibits more flexibility as the method calls are handled at run-time
  • Execution period is less
  • Execution period is more
  • Integrating the method call with the right method is completed in compile time polymorphism
  • Combining the correct method call with the right method is completed in runtime polymorphism
  • Appears during Operator Overloading and Method Overloading
  • Appears during Method Overriding

Advantages of Polymorphism

  • The main advantage of Polymorphism is code reusability; once a class is defined, it is used to construct an object several times.
  • Compile Time Polymorphism improves code readability by allowing substantially identical functions to have the same name, making it easier to comprehend the methods.
  • The same method can be used in parent and child classes in Runtime Polymorphism.
  • The code is simple to debug. Polymorphism provides computation with the required structure and regularity, making debugging easier.

CONCLUSION

Being one of the core concepts of OOP (Object-Oriented Programming), Polymorphism is an irreplaceable part of programming. Check out the UNext Jigsaw’s Postgraduate Certificate Program in Full Stack Development designed to aid learners in developing the mindset & competencies of a UI Developer & MEAN/MERN Stack Developer and transform them into well-rounded Full Stack Developer.

Related Articles

loader
Please wait while your application is being created.
Request Callback