Method Overloading in Java
What is Method Overloading?
Method overloading is a way to simplify methods by being able to use the same method name but change the parameters in the method. You can overload methods with different parameter types or with a different number of parameters. Method overloading is supported with both static methods and instance methods.
Method overloading isn't to be confused with method overriding. Method overriding is where you have a method in a superclass and override its implementation in a subclass.
Different Parameter Types
You can define multiple methods with the same name but with different types. Without method overloading, you would have code like the following:
public class MyClass {
public void printString(final String value) {
}
public void printInt(final int value) {
}
}
The only thing changing between these methods is the type that is passed to the method. With method overloading, you can use the same method name but with different parameter types. The previous example can be written with the following:
public class MyClass {
public void print(final String value) {
}
public void print(final int value) {
}
}
Different Number of Parameters
You can also overload methods by having a different number of parameters.
public class MyClass {
public int sum(final int num1, final int num2) {
return num1 + num2;
}
public int sum(
final int num1,
final int num2,
final int num3) {
return num1 + num2 + num3;
}
}
When designing methods that are overloaded based on the number of parameters, you want to put the new parameter at the end when you can.
public void MyClass {
public void method() {
}
public void method(final String s) {
}
public void method(final String s, final int x) {
}
public void method(final String s, final int x, final int y) {
}
}
Don't add method parameters anywhere but the end unless it makes sense to do so.
Different Return Type
When overloading methods, you cannot have the same method signature and only change the return type. If you do this, you will get a compiler error.
public class MyClass {
public void myMethod() {
}
// Compiler Error:
// method myMethod() is already defined in class MyClass
public boolean myMethod() {
}
}
Conclusion
Method overloading is a powerful feature that is great to be able to simplify your methods. Without it, you would have longer method names that would be confusing and poorly named because you would have to have type information in the name.