Polymorphism in Java : Free Java tutorials

Polymorphism is poly + morphism. Poly means multiple and morphism is form. So, polymorphism represents multiple forms. It is essentially one name but multiple forms. In Java, Polymorphism is the ability of an object to take on many forms.

Type 1:

The method name is same but we can take different types of arguments. This concept is method overloading.

It is also known as compiletime or static polymorphism which has two aspects of method overloading as well as method hiding.

Java has many inbuilt overloaded methods which work on the principle of compile-time polymorphism.

abs() method is one example of static polymorphism. This method returns the absolute value of a number where a number can be float, int, long etc.

Java has 3 following inbuilt overloaded methods in Java.Lang.Math class.

public int abs(int), public float abs(float) and public long abs(long).

These 3 methods have the same name but different return types and hence they are overloaded methods.

Type 2:

The method signature is same. But parent class and child class implementation of the method differs. This concept is method overriding. It is also known as runtime or dynamic polymorphism.

// Parent class
class Parent
{
	// Overridden parent class method
	public void method()
        {
	      System.out.println(“Parent Method”);
        }	 
}

// Child class
class Child
{
	// Overriding child class method
	public void method()
        {
	      System.out.println(“Child Method”);
        }	 
}

Usage of parent reference to hold child object is also considered the concept of polymorphism.

Polymorphism-1

In Java, List class has 3 subclasses named ArrayList, LinkedList, and Vector. Further, Vector class has a subclass named Stack.

Using reference to List class, we can create objects of any subclasses of List class.

So, the parent class reference can be used to hold child object. But, by using that object, we can call only the methods defined in the parent class and we cannot call child specific methods.

However, by using child reference, we can call both the parent and child class methods.

Advantages of Polymorphism

  1. If we do not know exact runtime type of object, then we can use parent reference. Implementation becomes busy in such cases since parent reference can hold any child class object.
  2. It gives flexibility to the programmer.

Polymorphism and Two other pillars of OOP

Polymorphism-2

This is all about Polymorphism in Java. Hope you find this tutorial helpful.

Leave a Comment

Your email address will not be published. Required fields are marked *