method overloading means having multiple methods in the same class with the same name but different parameters. It lets you write code that is more flexible and easier to read.
📚 Why Overload a Method?
Sometimes, you want a method to do similar things but accept different types or numbers of inputs. Method overloading helps you achieve this without creating different method names for each version.
✅ Rules for Method Overloading:
- Same method name
- Different parameter list (type, number, or order)
- Can have different return types—but return type alone is not enough
🔧 Example:
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Method to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two doubles
double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(10, 20)); // Calls the first method
System.out.println(calc.add(10, 20, 30)); // Calls the second
System.out.println(calc.add(5.5, 4.5)); // Calls the third
}
}
🖨 Output:
30 60 10.0
Each add()
method is tailored to different inputs—same name, different behavior.