Method overloading lets you define multiple methods with the same name but different parameter lists. You can use it to perform a similar task with different inputs.
In this example, you will create three add() methods to add two integers, three integers, or two floating-point numbers.
Source code
public class MethodOverloadingExample {
void main() {
int twoIntegerSum = add(10, 20);
int threeIntegerSum = add(10, 20, 30);
double twoDoubleSum = add(2.5, 3.75);
IO.println("Sum of two integers: " + twoIntegerSum);
IO.println("Sum of three integers: " + threeIntegerSum);
IO.println("Sum of two doubles: " + twoDoubleSum);
}
int add(int first, int second) {
return first + second;
}
int add(int first, int second, int third) {
return first + second + third;
}
double add(double first, double second) {
return first + second;
}
}
Explanation
All three methods are named add(), but their parameter lists differ:
| Method | Parameters |
|---|---|
add(int first, int second) |
Two integers |
add(int first, int second, int third) |
Three integers |
add(double first, double second) |
Two doubles |
When you call an overloaded method, the compiler selects the applicable version based on the number and types of the arguments.
The following call passes two int values:
int twoIntegerSum = add(10, 20);
It selects add(int, int) and returns 30.
This call passes three int values:
int threeIntegerSum = add(10, 20, 30);
It selects add(int, int, int) and returns 60.
Finally, this call passes two double values:
double twoDoubleSum = add(2.5, 3.75);
It selects add(double, double) and returns 6.25.
Run the example
Compile and run the file:
javac MethodOverloadingExample.java
java MethodOverloadingExample
Output
Sum of two integers: 30
Sum of three integers: 60
Sum of two doubles: 6.25
Rules to remember
Overloaded methods must differ in the number, types, or order of their parameter types.
Changing only the parameter names does not create a different overload. Changing only the return type is also insufficient. For example, these two declarations cannot appear together in the same class:
int add(int first, int second) {
return first + second;
}
double add(int first, int second) {
return first + second;
}
Both methods have the same name and parameter types, so the compiler reports an error.
