exampracticeonline.com
Polymorphism

Polymorphism in Java

Polymorphism in java is a one of the OOPs concept by which we can perform a single action by different ways or in many (poly) forms. 

The term Polymorphism is derived from the two Greek word where poly + morphos where poly means many and morphos means forms.

The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

Example of Polymorphism

Suppose we have a Shape class that has a draw() method. Since this is a generic class so we can’t give it implementation. We just declare the functionality of Share class and drive class will give the implementation of draw() method according to their requirement.

Now say let we have three subclass of Share class. All three class extends Share class and provide implementation of draw() method in all three class.

4

As you can see that although we had the common action for all subclasses draw() but there were different ways to do the same action.

This is a perfect example of polymorphism (feature that allows us to perform a single action in different ways). It would not make any sense to just call the generic draw() method as each class has a different shape. Thus we can say that the action this method performs is based on the type of object.

So, Circle class draws a circle, Rectangle class draws a Rectangle and Triangle class draws a Triangle.

Implementation of Polymorphism

public class Shape{
   public void draw(){
      System.out.println("Drwaing a shape");   
   }
}

class Circle extends Shape{
    @Override
    public void draw(){
        System.out.println("Drwaing a circle shape");
    }
    public static void main(String args[]){
        Shape obj = new Circle();
        obj.draw();
    }
}

Output: Drwaing a circle shape


class Rectangle extends Shape{
    @Override
    public void draw(){
        System.out.println("Drwaing a rectangle shape");
    }
    public static void main(String args[]){
        Shape obj = new Rectangle();
        obj.draw();
    }
}

Output: Drwaing a rectangle shape


class Triangle extends Shape{
    @Override
    public void draw(){
        System.out.println("Drwaing a triangle shape");
    }
    public static void main(String args[]){
        Triangle obj = new Circle();
        obj.draw();
    }
}

Output: Drwaing a triangle shape

Polymorphism can be achieved in two ways

1. Method Overloading(Compile time Polymorphism) - Compile time polymorphism is also called static binding because method bind at compile time. 

Overloading in details

2. Method Overriding(Run time Polymorphism) - Run time polymorphism is also called dynamic binding because method bind dynamically at run time.

Overriding in details