Polymorphism is the process of doing the same thing in different ways. In Java, Polymorphism can achieve using method overloading and method overriding
Types of Polymorphism in Java:
1. Complie-Time Polymorphism or Static Polymorphism: In Java compile-time polymorphism can achieve through method overloading.
2. Runtime Polymorphism or dynamic Polymorphism: In Java compile-time polymorphism can achieve through method overriding.
Method overloading:
Let's understand the method overloading.
Suppose we need to perform a simple task which is addition of 2 number or 3 number or concat 2 string.
for this we can create 3 method.
public static void addTwoNumber(int a, int b){
// method body
}
public static void addThreeNumber(int a, int b, int c){
// method body
}
public static void concatTwoString(String a, String b){
// method body
}
But this is not a perfect way a to do this similar task. Another best way to do this is method overloading.
With the help of method overloading concept we can create multiple method with the same name but different parameter.
public static void addition(int a, int b){
// method body
}
public static void addition(int a, int b, int c){
// method body
}
public static void addition(String a, String b){
// method body
}
here each method parameter should different from one another. Now we don't need to call three another methods. we can call one method. The specific method will work based on the parameters sent while calling
addition(345,3453); // this will work for the first method
addition(345,3453, 3453); // this will work for the second method
addition("Hello ","World"); // this will work for the third method
Method overriding:
Let's understand the method overriding.
In inheritance, suppose you have a method in super class and you over write the method in the subclass. This type of polymorphism called method overriding. The over written method in the subclass shoud have the same name, same return type, same parameter list as the method in the super class.
Example:
// Super class Animal
class Animal {
// Superclass method sound
void sound() {
System.out.println("The animal makes a sound");
}
}
// Subclass Dog and super class Animal
class Dog extends Animal {
// Overridden method sound in subclass
@Override
void sound() {
System.out.println("The dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
}
}