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 compile–time 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 run–time 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.
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
- 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.
- It gives flexibility to the programmer.
Polymorphism and Two other pillars of OOP
This is all about Polymorphism in Java. Hope you find this tutorial helpful.