Polymorphism means one thing in many forms. There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.
Runtime Polymorphism is also know as dynamic polymorphism this can be achived by overriding methods in java.
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.
Usage
package com.java.session.eight;
public class Examples {
public static void main(String[] args) {
Splendor splendor = new Splendor();
splendor.run();
Bike b = new Splendor(); // Upcasting achieved overriding
b.run();
}
}
class Bike {
public void run() {
System.out.println("running");
}
}
class Splendor extends Bike {
public void run() {
System.out.println("Splendor is running");
}
}
compile-time Polymorphism is also know as static polymorphism this can be achived by overloading methods in java.
If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
Advantage of method overloading
package com.java.session.eight;
public class MethodOverloadingExample {
int add(int a,int b) {
return a+b;
}
int add(int a,int b,int c) {
return a+b+c;
}
public static void main(String[] args){
MethodOverloadingExample obj = new MethodOverloadingExample();
int method1Result = obj.add(10, 20);
System.out.println(method1Result);
int method2Result = obj.add(10, 30, 60);
System.out.println(method2Result);
}
}
public class MethodOverloadingExample {
int add(int a,int b) {
return a+b;
}
double add(double a,double b) {
return a+b;
}
public static void main(String[] args){
MethodOverloadingExample obj = new MethodOverloadingExample();
int method1Result = obj.add(10, 20);
System.out.println(method1Result);
double method2Result = obj.add(10.0, 30.9);
System.out.println(method2Result);
}
}