Java
Method overloading
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.
Exercise 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.
Show example 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));
Test yourself
-
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)
- int add(int a, int b) and int sum(int a, int b)
Show answer
int add(int a, int b) and int add(int x, int y) — When parameter types differ, the signature differs.
-
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; }
Show answer
static int add(int a, int b) { return a + b; }
static double add(double a, double b) { return a + b; }
-
Match call to selected signature
- 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
Next lesson: Scope