Learn Method Overloading in Java (With Examples)
Method overloading in Java is a feature that lets a class have more than one method with the same name, as long as their parameter lists are different. It's a form of compile-time (static) polymorphism.
Rules for Method Overloading
- Overloaded methods must have the same name but a different number, type, or order of parameters
- Return type alone cannot be used to overload a method
- Overloaded methods can have different access modifiers or throw different exceptions
Example: Different Number of Parameters
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
Example: Different Parameter Types
class Printer {
void show(int value) {
System.out.println("Integer: " + value);
}
void show(String value) {
System.out.println("String: " + value);
}
}
Why Use Method Overloading?
- Improves code readability by using one intuitive method name for related operations
- Lets a method handle different types or numbers of inputs without renaming it
- Forms the basis of compile-time polymorphism in Java
The compiler decides which overloaded method to call at compile time based on the arguments passed — this is why overloading is also called static binding.
Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.