Method Overloading in Java
Method overloading means using the same method name for similar tasks, but with different parameter lists. Java chooses the correct method from the arguments used in the call.
Overloading by Number of Parameters
Two methods can have the same name when they accept a different number of parameters.
Example 1: Adding Two or Three Numbers
class OverloadingDemo {
// First add method: two parameters
static int add(int a, int b) {
return a + b;
}
// Second add method: three parameters
static int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
System.out.println(add(5, 10));
System.out.println(add(5, 10, 15));
}
}
Output:
15
30
Explanation:
Both methods are named add(). The first call has two arguments, so Java uses add(int, int). The second call has three arguments, so Java uses add(int, int, int).
Overloading by Parameter Type
A method can also be overloaded by changing the data types of its parameters.
Example 2: Adding Integers and Decimals
class OverloadingDemo {
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(4, 6));
System.out.println(add(2.5, 3.5));
}
}
Output:
10
6.0
Explanation:
Java uses the parameter types to select the method: integer arguments call add(int, int), while decimal arguments call add(double, double).
Rules of Method Overloading
- Overloaded methods must have different parameter lists.
- You can change the number of parameters, parameter types, or order of different parameter types.
- Changing only the return type does not create an overloaded method.
- Changing only parameter names does not create an overloaded method.
Invalid Example: Only Return Type Changed
static int calculate(int a, int b) {
return a + b;
}
// Invalid: same method name and same parameter types
static double calculate(int x, int y) {
return x + y;
}
Explanation:
This produces a compilation error. Both methods have the same name and the same parameter types, so Java cannot choose between them. A different return type alone is not enough.
Key Points:
- Method overloading lets one method name handle similar tasks.
- Java selects an overloaded method using the number, types, and order of arguments.
- It is also called compile-time polymorphism.