Java Tutorial


OOPS concept


Collection

Java Polymorphism

Polymorphism is made of two words poly and morphs. "Poly" means many and "morphs" means form. So polymorphism means many forms. The word 'Polymorphism' literally means 'a state of having many shapes'.

There are two types of Polymorphism in Java

  • Compile time polymorphism (Static binding)
  • Run time polymorphism (Dynamic Binding)

Method overloading is an example of static polymorphism, while method overriding is an example of dynamic polymorphism.

A common example of polymorphism is when a parent class reference is used to refer to a child class object.

Note: An object in Java that passes more than one IS-A tests is polymorphic in nature.

Compile Time (Static) Polymorphism

Method overloading is an example of static polymorphism. Method overloading means having several methods with same name but with different parameters or argument list.

Java decides which method to invoke by checking the argument list and this is done at compile time. Therefore it is known as compile time polymorphism or static polymorphism.

Example


class Addition{

public int add(int a, int b)
 {return a+b;}

public int add(int a, int b, int c)
 {return a+b+c;}

public int add(float a, float b)
 {return (int)a+b;}

}

class TestExample{
public static void main(String args[]){
  Addition a = new Addition();  
  System.out.println(a.add(2,4)); //method 1
  System.out.println(a.add(2,4,8)); //method 2
  System.out.println(a.add(2.6,4.7));//method 3

 }
}

According to the parameters passed java invokes the right method. If the parameters doesn't match any of the method definition, it will show an error.

Run Time (Dynamic) Polymorphism

Method overriding is an example of dynamic polymorphism. Must check this section for detail. In method overriding a child class has same method as in parent class.

Lets understand how polymorphism is implemented. Consider the below example

class Shape{
 public void show(){
  System.out.println("This is a Shape.");
  }
}

class Circle extends Shape{
 public void show(){
  System.out.println("This shape is a circle.");
 }
}

class TestExample{
 public static void main(String args[]){
  Shape shape = new Circle();
  shape.show(); // child class method
  shape = new Shape();
  shape.show(); //parent class method
 }
}

In the above example, the reference type is Shape and the object being referenced is Circle. So, when show() method is called, Java waits until runtime to determine which object is actually being pointed to by the reference. Here the object is of Circle class so the method of class Circle is invoked. In the next case, the reference is still of Shape class but now the object is also of Shape class, therefore this time the method of parent class is invoked.

This is also known as Dynamic binding or Late binding because the decision to invoke method is taken at runtime.

Advertisment

Share


Advertisement