What is compile-time polymorphism?
- Compile-time polymorphism means the method is selected at compile time, not at runtime.
What is Method Overloading?
Method Overloading means having
multiple methods with the same name but different parametersin the same class.It is a type of Compile-Time Polymorphism.
Example:
public class MethodOverloading{
public void add(int i, int j){
System.out.println(i+j);
}
public void add(int i, String j){
System.out.println(i+j);
}
public void add(int i, int j, String b){
System.out.println(i+j+b);
}
public void add(int i, String j, int k, String l){
System.out.println(i+k+j+l);
}
public void add(String l){
System.out.println(l);
}
public static void main(String[] args){
MethodOverloading sp= new MethodOverloading();
sp.add(8, 10);
sp.add(8,"Virat");
sp.add(8, 10, "Virat");
sp.add(8, "Virat", 10, "Kohli");
sp.add(8 + 10 + "Virat");
}
}
Why do we go to Method Overloading?
- Improves code readability.
- Avoids creating multiple method names.
- To perform the same task in different ways.
Top comments (0)