Polymorphism

Polymorphism in Java is a concept which define the term ‘One in many forms’. In Java there are two types of polymorphism such as compile time polymorphism and run time polymorphism, also we can say early binding and late binding. In Java, we can perform polymorphism by method overloading and method overriding.

Compile Time Polymorphism or Static Polymorphism
Compile Time Polymorphism means we can use the same method name for multiple purpose.Method overloading in Java is the example of Compile Time Polymorphism.
Let us see an example:

class Addition
{
  void add(int num1, int num2) {
    System.out.println("Addition of integer values " + (num1+num2));
  }
  void add(double num1, double num2) {
    System.out.println("Addition of double values " + (num1+num2));
  }
  void add(String s1, String s2) {
    System.out.println("Addition of string objects " + (s1+s2));
  }
}
public class CompiletimePolymorphismTest {

  public static void main(String[] args) {
    Addition add1 = new Addition();
    add1.add(10, 10);
    add1.add(10.75, 10.50);
    add1.add("Huge ", "Learning");
  }
}

Output:

Addition of integer values 20
Addition of double values 21.25
Addition of string objects Huge Learning

Run Time Polymorphism or Dynamic Polymorphism
Runtime polymorphism or Dynamic Polymorphism is a process in which a call to an overridden method at runtime rather than compile-time. Method overriding in Java is the example of Run Time Polymorphism.

Let us see an example:

class Shape{  
  void draw(){
    System.out.println("drawing shape");
  }  
}  
class Circle extends Shape{  
  void draw(){
    System.out.println("drawing circle");
  }  
}  
class Triangle extends Shape{  
  void draw(){
    System.out.println("drawing triangle");
  }  
}  
class Rectangle extends Shape{  
  void draw(){
    System.out.println("drawing rectangle");
  }  
}  

public class RuntimePolymorphismTest {

  public static void main(String[] args) {
    Shape shape = new Shape();
    shape.draw();

    shape = new Circle();
    shape.draw();

    shape = new Triangle();
    shape.draw();

    shape = new Rectangle();
    shape.draw();

  }

}

Output:

drawing shape
drawing circle
drawing triangle
drawing rectangle