What is method overloading?
Method overloading is a feature that allows a class to have more than one method having the same name, but with different arguments list.
class MyMath {
public static void main(String[] args) {
int a = calculate(5,6);
int b = calculate(5,6,"subtract");
System.out.println(a);
System.out.println(b);
}
public static int calculate(int a, int b) {
return a+b;
}
public static int calculate(int a, int b, String method) {
switch (method) {
case "add":
return a+b;
case "subtract":
return a-b;
}
return 0;
}
}
In the above class, you see two methods with the same name calculate. However, the parameters list is different. First calculate method takes two integer parameters and the second method takes two integer parameters and one string parameter.
Rules for Method Overloading
- Method Name: Must have the same method name.
- Parameter List: Must have a different parameter list (e.g., different number of parameters, different types of parameters, or a different order of types).
- Return Type: The return type can be different. The return type alone is not enough to distinguish overloaded methods.
- Access Modifiers: The access modifiers can be different.