Careeroza
Method Overloading
Same Name, Different Parameters
Overloading means several methods with the same name but different parameter lists (number, type or order of parameters). Java picks the right one at compile time from the arguments.
Example
public class Main {
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
static String add(String a, String b) {
return a + " " + b;
}
public static void main(String[] args) {
System.out.println(add(2, 3));
System.out.println(add(2.5, 3.1));
System.out.println(add(1, 2, 3));
System.out.println(add("Hello", "Java"));
}
}Output
5 5.6 6 Hello Java
What Counts as Overloading
| Change | Valid overload? |
|---|---|
| different number of parameters | yes |
| different parameter types | yes |
different order of types (int, String) vs (String, int) | yes |
| only the return type differs | no, compile error |
| only parameter names differ | no, compile error |
Tip: System.out.println itself is overloaded: there are versions for int, double, char, String, Object and more.