Polymorphism in Java

The word polymorphism means having many forms. This feature of object-oriented programming allows us to perform a single action in different ways.  In other words, polymorphism allows you to define one interface and have many implementations. The word “poly” means many and “morphs” means forms, which means multiple forms.

In Java, it is mainly divided into two types:

  • Compile  time Polymorphism
  • Runtime Polymorphism

Compile time polymorphism:

It is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading.

Function overloading :

When there are multiple functions with the same name but different parameters, then these functions are said to be overloaded. Functions can be overloaded by the change in the number of arguments or/and changes in the type of arguments.

1. By using different types of arguments

// A simple java program for Method overloading
class Overload
{
// Method with integer parameters
static int Add(int a, int b)
{
return a + b;
}
// Method with the same name but double parameters
static double Add(double a, double b)
{
return a + b;
}
}
class Test {
public static void main(String[] args)
{
System.out.println(Overload.Add(2, 4));
System.out.println(Overload.Add(5.5, 6.3));
}
}

Output:
6
11.8

2. By using different numbers of arguments

// Java program for Method overloading
class Overload {
// Method with 2 parameters
static int Add(int a, int b)
{
return a + b;
}
// Method with the same name but 3 parameters
static int Add(int a, int b, int c)
{
return a + b + c;
}
}
class Test {
public static void main(String[] args)
{
System.out.println(Overload.Add(2, 4));
System.out.println(Overload.Add(2, 7, 3));
}
}

Output:
6
12

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, on the other hand, occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.

Example:
//A simple  java program for Method overridding
class ParentClass {
void Display()
{
System.out.println("I am the parent");
}
}
class SubClass1 extends ParentClass {
void Display()
{
System.out.println("I am the child1");
}
}
class SubClass2 extends ParentClass {
void Display()
{
System.out.println("I am the child2");
}
}
class Poly {
public static void main(String[] args)
{
ParentClass a;
a = new SubClass1();
a.Display();
a = new SubClass2();
a.Display();
}
}

Output:
I am the child1
I am the child2

Conclusion:

This is how we can easily make functions polymorphic and these functions can behave in the way they are wanted to.