Types of Polymorphism
You can perform Polymorphism in Java via two different methods:
Method Overloading
Method Overriding
What is Method Overloading in Java?
Method overloading is the process that can create multiple methods of the same name in the same class, and all the methods work in different ways. Method overloading occurs when there is more than one method of the same name in the class.
Example of Method Overloading in Java
class Shapes {
public void area() {
System.out.println("Find area ");
}
public void area(int r) {
System.out.println("Circle area = "+3.14*r*r);
}
public void area(double b, double h) {
System.out.println("Triangle area="+0.5*b*h);
}
public void area(int l, int b) {
System.out.println("Rectangle area="+l*b);
}
}
class Main {
public static void main(String[] args) {
Shapes myShape = new Shapes(); // Create a Shapes object
myShape.area();
myShape.area(5);
myShape.area(6.0,1.2);
myShape.area(6,2);
}
}
Output:
Find area
Circle area = 78.5
Triangle area=3.60
Rectangle area=12
What is Method Overriding in Java?
Method overriding is the process when the subclass or a child class has the same method as declared in the parent class.
Example of Method Overriding in Java
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is moving");}
}
//Creating a child class
class Car2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("car is running safely");}
public static void main(String args[]){
Car2 obj = new Car2();//creating object
obj.run();//calling method
}
}
Output:
Car is running safely
Also, Polymorphism in Java can be classified into two types, i.e:
Static/Compile-Time Polymorphism
Dynamic/Runtime Polymorphism