Polymorphism in Java

Polymorphism is a Greek word which means "several forms". It is the most important feature of any object-oriented programming language.

Java supports two types of polymorphism-

  1. Compile time Polymorphism-
    • It is also known as static binding or early binding.
    • Here, method behavior is resolved at the compile time.
    • Method Overloading is an example of compile time polymorphism.
  2. Runtime Polymorphism-
    • It is also known as dynamic binding or late binding.
    • Here, different forms of a single entity are determined at the runtime.
    • Method Overriding is an example of run time polymorphism.

Runtime Polymorphism in Java

Reference variable of a superclass can refer to an object of a subclass. When inheritance is performed, the instance variables are bounded at compile time, and methods are bounded at runtime.

Example of Runtime Polymorphism with method

class Shape
{
	public void display()
	{
		System.out.println("I am a shape");
	}
}
class Square extends Shape
{
	public void display()
	{
		System.out.println("I am a square");
	}
	public static void main(String args[])
	{
		Shape s = new Shape();		
		s.display();
		s = new Square();
		s.display();
	}
}

Output

I am a shape
I am a square

In the above example, initially the type of reference variable "s" and the type of object referenced by it are the same(Shape), so there is no confusion in the method call.

Later we assign reference variable "s" to an object of Square class. Even though we are calling display() method but JRE is aware that method is called on a Square object so overridden method display() in the Square class is called.

Example of Runtime Polymorphism with variable

class Car
{
	int speedlimit = 90;	
}
class Hyundai extends Car
{
	int speedlimit = 200;	
	public static void main(String args[])
	{
		Car c = new Car();		
		System.out.println("Speedlimit = "+c.speedlimit);
		c = new Hyundai();
		System.out.println("Speedlimit = "+c.speedlimit);
	}
}

Output

Speedlimit = 90
Speedlimit = 90

Since, variables are bounded at compile time, so the type of object that the reference variable "c" is pointing does not make any difference. And in both the cases, it will print speedlimit = 90