The simple meaning of polymorphism is having different forms or shapes.
A real-life example of polymorphism can be the moon as viewed from earth.
The property of moon to have different shapes, i.e the phases of the moon.
In Object Oriented Programming, polymorphism is a way to perform a single action in different ways.
In Java, polymorphism can be viewed as the capability of methods to do different jobs based on the object properties.
Does that sound similar to anything?
Do you remember method overloading?
Method overloading falls into polymorphism.
As it allows us to define a thing and use it in different manners.
But wait, if method overloading is a type of polymorphism then what about method overriding?
Method overriding also allows us to use the same method in different ways.
Thus, method overriding also falls into polymorphism.
Polymorphism is of two types –
- Static polymorphism
- Dynamic Polymorphism.
Static Polymorphism
Static polymorphism also known as compile-time polymorphism is achieved through method overloading.
At compile time, Java knows which method to invoke by checking the method signatures thus it is known as compile time polymorphism.
Do you remember the overloading example we studied?
class Main {
public static void dontOverloadMe(){
System.out.println(“Please, don’t.”);
}
public static void dontOverloadMe(String laugh){
System.out.println(“Oops! Couldn’t hold it for long. “+ laugh);
}
}
Every method overloading operation ultimately is a polymorphism, just like the above one.
Dynamic Polymorphism
Whereas dynamic polymorphism or run time polymorphism is achieved through method overriding.
In case of method overriding the method to call is determined at runtime, thus it is known as runtime or dynamic polymorphism.
class ParentClass{
public void oldMethod(){
System.out.println(“Parents rock.”);
}
}
class ChildClass extends ParentClass{
public void oldMethod(){
System.out.println(“Children rock. “);
}
}
This snippet in which the ChildClass extends ParentClass and oldMethod() is overridden is an example of runtime polymorphism.
Polymorphism is unavoidable in Java.
Overloading, overriding, extending classes all contribute to polymorphism in the end.
Wow! We are doing very good and completed a long journey. Heard that before?
To summarize
- Polymorphism is a way to perform a single action in different ways.
- Polymorphism is of two types – Static polymorphism and Dynamic Polymorphism.
- Static polymorphism also known as compile-time polymorphism is achieved through method overloading.
- Dynamic polymorphism or runtime polymorphism is achieved through method overriding.