Polymorphism in Java

Polymorphism in Java, Java Object-Oriented Programming, Method Overloading, Method Overriding, Compile tin & Run-time Polymorphism in Java.

Polymorphism in Java is a concept by which we can perform a single action in different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word “poly” means many and “morphs” means forms. So polymorphism means many forms.

Java Polymorphism

The existence of Object behavior in many forms is called Polymorphism.

Polymorphism – Many ways/forms

Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.

We have two types of Polymorphism:
1. Compile Time Polymorphism/Method OverLoading
2. Run-Time Polymorphism/Method Overriding

1. Compile Time Polymorphism

If two are more methods with the same name in the same class but differ in the following ways,

a. Number Arguments
b. Type of Arguments

Example:

package package1;

public class Class1 {
public void add (int a, int b) {
System.out.println(a+b);
}
public void add (int a, int b, int c) {
System.out.println(a+b+c);
}
public void add (double a, double b) {
System.out.println(a+b);
}
public static void main (String []args) {
Class1 obj = new Class1();

obj.add(100, 299);//399
obj.add(100, 200, 300);//600
obj.add(10.4, 29.9);//40.3
}

}

2. Run Time Polymorphism

If two or more methods wit same name that available in the parent class and child class.

Example:

Class1:

package package1;

public class Class1 {
int a=100, b=200;
public void add () {
System.out.println(a+b);
}

}

Class2:

package package1;

public class Class2 extends Class1{
int a=1, b=2;
public void add () {
System.out.println(a+b);
}
public static void main(String[] args) {
Class2 obj = new Class2();
int x=obj.b;
System.out.println(x);//2
System.out.println(obj.b);//2
obj.add();//3
}
}

Advantages of Polymorphism in Java:

It provides reusability to the code. The classes that are written, tested, and implemented can be reused multiple times. This, in turn, saves a lot of time for the coder. Also, the code can be changed without affecting the original code.

A single variable can be used to store multiple data values. The value of a variable inherited from the superclass into the subclass can be changed without changing that variable’s value in the superclass or any other subclasses.

With lesser lines of code, it becomes easier for the programmer to debug the code.


Java Tutorial

Java Videos

Follow me on social media:

1 thought on “Polymorphism in Java”

Leave a Comment