Java Method Overloading
In this page:
Overloading by Parameter Count
Overloading lets several methods share the exact same name as long as their parameter lists differ -- here, differing purely in how many parameters each version accepts, like add(int, int) versus add(int, int, int).
Example: Overloading by Parameter Count
public class Main {
static int add(int a, int b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
System.out.println(add(1, 2));
System.out.println(add(1, 2, 3));
}
}
Login to try C/C++/Java/PHP code in the editor
Overloading by Parameter Type
You can also overload by keeping the same parameter count but changing the types, like add(int, int) versus add(double, double), letting one method name handle several different kinds of input naturally.
Example: Overloading by Parameter Type
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(1, 2));
System.out.println(add(1.5, 2.5));
}
}
Login to try C/C++/Java/PHP code in the editor
Overloading by Parameter Order
Even keeping the same types and count but swapping their order, like process(String, int) versus process(int, String), counts as a distinct, valid overload as far as the compiler is concerned.
Example: Overloading by Parameter Order
public class Main {
static void process(String s, int n) {
System.out.println(s + n);
}
static void process(int n, String s) {
System.out.println(n + s);
}
public static void main(String[] args) {
process("Item", 5);
process(5, "Item");
}
}
Login to try C/C++/Java/PHP code in the editor
Automatic Type Promotion
When a call doesn't exactly match any overload's parameter types, Java automatically widens the arguments (like int to double) to find the closest compatible version rather than failing to compile.
Example: Automatic Type Promotion
public class Main {
static double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(2, 3)); // ints widened to double
}
}
Login to try C/C++/Java/PHP code in the editor
Best Practices in Overloading
Overloads should all represent the same underlying operation with different inputs -- using the same method name for genuinely unrelated behaviors defeats the purpose and makes the API confusing to use correctly.
Example: Best Practices in Overloading
public class Main {
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b; // same operation, different input types
}
public static void main(String[] args) {
System.out.println(add(2, 3));
System.out.println(add(2.0, 3.0));
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: