Java Method Overloading
Method overloading lets you give several methods the same name, as long as their parameter lists differ. Java figures out which version to run based on the arguments you pass. This keeps related operations under one clear, easy-to-remember name.
What overloading solves
Suppose you want to add two numbers, but sometimes they are integers and sometimes they are decimals. Without overloading you might invent separate names like addInts and addDoubles. With overloading, you can call both of them add, and Java picks the right one automatically.
Two methods, one name
public class Main {
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(5, 3)); // uses the int version
System.out.println(add(5.5, 3.2)); // uses the double version
}
}
// Output:
// 8
// 8.7What counts as a different signature
The combination of a method's name and its parameter list is called its signature. To overload a method, the parameter lists must differ in the number of parameters, their types, or their order. The compiler uses these differences to decide which method to call.
- Different number of parameters: add(int, int) vs add(int, int, int)
- Different parameter types: print(int) vs print(String)
- Different order of types: format(int, String) vs format(String, int)
Overloading with a different count
Same name, different number of parameters
public class Main {
static int sum(int a, int b) {
return a + b;
}
static int sum(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
System.out.println(sum(2, 3)); // 5
System.out.println(sum(2, 3, 4)); // 9
}
}
// Output:
// 5
// 9Exercise: Java Method Overloading
What is required for two methods with the same name to be a legal overload?