Java Polymorphism


Polymorphism is the ability of an object to take on many forms, i.e. performing one task by different ways.

The word polymorphism is made up of “poly + morphs” which means many forms.

Polymorphism is used in OOP when a parent class reference is used to refer to a child class object.

In java, polymorphism is achieved by method overloading and method overriding.


There are 2 types of polymorphism in java:

  1. Compile time polymorphism: It is a process when we overload static method in java.
  2. Run time polymorphism: It is a process in which a call to an overridden method is resolved at runtime rather than compile time. In this process, an overridden method is called through the reference variable of the super class. The method to be called is based on the reference object referenced by the variable.

Upcasting: When a reference variable of a parent class refers to the object of Child class.

Example:

class A{}  
class B extends A{}  

// upcasting
A a = new B();

Example:We are creating two classes ‘Car’ and ‘Bike’. Bike class extends Car class and overrides its speed() method. We are calling the speed() method by the reference variable of its Parent class i.e. Car.

Since method invocation is determined by the Java Virtual Machine (JVM) during run time and not by compiler, it is known as runtime polymorphism.

class Car
{  
	void speed()
    {
        System.out.println("Max. Speed is 140Kmph.");
    }
}

class Bike extends Car
{  
  void speed()
    {
        System.out.println("Max. Speed is 90Kmph.");
    }

    public static void main(String args[])
    {
        // upcasting
        Car c = new Bike();

        // will invoke speed method of Bike class
        c.speed();
    }
}

Output:

Max. Speed is 90Kmph.

NOTE: Only Method is overridden not the data members, so runtime polymorphism can't be achieved by data members.

Example: Let both the classes have a data member ‘speed’, we are accessing the data member through the reference variable of parent class which refers to the subclass object. Since we are accessing the data member, which is not overridden, hence it will always access the data member of the parent class.

class Car
{  
    int speed=140;  
}

class Bike extends Car
{  
    int speed=90;

    public static void main(String args[])
    {
  		Car c=new Bike();  
 		System.out.println(c.speed);
    }
}

Output:

140