Method overloading
- Java course
- Beginner
- Lesson 74/116
- 4 min
Learn same-named methods.
Method overloading
You can define methods with the same name but different parameters. This is called overloading. The compiler picks the right method based on the argument types at the call site.
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}The signature = name + parameter types. As long as the signature differs, you can reuse the same name. Return type is not part of the signature.
Which overload is called?
The argument types at the call site are matched by the compiler to the best signature. If types match exactly, that method is chosen; otherwise widening (int → double) is tried.
add(3, 4); // int add(int, int)
add(3.0, 4.0); // double add(double, double)
add(3, 4.0); // double add(double, double)In the last call there is an int and a double; the int is widened to double and the double version is chosen. If ambiguous, you get a compile error.
Practice Two add overloads
Define two add methods: int add(int a, int b) and double add(double a, double b). Both return the sum. Call add(3, 4) and add(2.5, 1.5) from main and print the results on separate lines.
Starter code
public class Main {
public static void main(String[] args) {
// Try the add method with two different calls and print the results
}
// Define int add(int, int)
// Define double add(double, double)
}Sample solution
static int add(int a, int b) { return a + b; }
static double add(double a, double b) { return a + b; }
// inside main:
System.out.println(add(3, 4));
System.out.println(add(2.5, 1.5));Expected output
7 4.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which pair forms an overload?
- int add(int a, int b) and double add(double a, double b)
- int add(int a, int b) and double add(int a, int b)
- int add(int a, int b) and int add(int x, int y) Correct answer
- int add(int a, int b) and int sum(int a, int b)
Explanation: When parameter types differ, the signature differs.
2 Fill in the blank: double version
static int add(int a, int b) { return a + b; }
static ____ add(double a, double b) { return a + b; }
static int add(int a, int b) { return a + b; }
static double add(double a, double b) { return a + b; }
Explanation: A double-parameter version returns double.
3 Match call to selected signature
| Term | Meaning |
|---|---|
add(3, 4) |
int version chosen |
add(3.0, 4.0) |
double version chosen |
add(3, 4.0) |
int widens to double |
add("a", "b") |
Compile error |