Introduction
In Java, method overloading is a concept where you can define multiple methods with the same name but different parameters in the same class.
It is one of the important features of compile-time polymorphism.
Method overloading means creating multiple methods with the same name but different parameter lists and diffrent data type.
Why Do We Need Method Overloading?
Imagine you want to perform the same operation (like addition) with different inputs:
- Add 2 numbers
- Add 3 numbers
- Add decimal numbers
Instead of using different method names, we can use one method name.
class Calculator {
// Method 1
int add(int a, int b) {
return a + b;
}
// Method 2
int add(int a, int b, int c) {
return a + b + c;
}
// Method 3
double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator obj = new Calculator();
System.out.println(obj.add(10, 20)); // 30
System.out.println(obj.add(10, 20, 30)); // 60
System.out.println(obj.add(5.5, 2.5)); // 8.0
}
}
How Java Decides Which Method to Call
Java checks based on:
- Number of parameters
- Type of parameters
- Order of parameters
This happens at compile time.
Rules of Method Overloading
✔ Method name must be same
✔ Parameters must be different (type / number / order)
Return type alone is NOT enough
int add(int a, int b)
double add(int a, int b) // Not allowed
Real-Life Example
Think like a remote control
- Same button → "Volume"
- But action changes:
- Press once → increase little
- Hold → increase continuously
Same name, different behavior = Overloading
Top comments (0)