Method Overloading in Java allows multiple methods with the same name to exist in a class, as long as their parameter lists are different. It improves code readability and supports compile-time polymorphism.
In method overloading, Java determines which method to call based on the method signature. The signature includes the method name and parameter list, but not the return type.
// Demonstrates method overloading using different parameter lists
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(10, 20));
System.out.println(calc.add(10, 20, 30));
System.out.println(calc.add(5.5, 4.5));
}
}
30
60
10.0
Java selects the correct add() method based on the number and type of arguments passed during the method call.
Select a method call below to see which Java method signature gets triggered based on the arguments.
int add(int a, int b) { ... }int add(int a, int b, int c) { ... }double add(double a, double b) { ... }