Method Overloading
Method Overloading allows multiple methods to have the same name with different parameters.
The Concept
Imagine you want to create a method that adds numbers. Instead of defining
addIntegers() and addDoubles(), you can simply define
add() for both.
int add(int x, int y) { ... }
double add(double x, double y) { ... }
How Java Distinguishes Them
Java differentiates overloaded methods based on the number and type of parameters. The return type alone is NOT enough to overload a method.
| Method Signature | Valid Overload? | Reason |
|---|---|---|
void print(String s) |
Original | - |
void print(int i) |
Yes | Different parameter type (int vs String) |
void print(String s, int i) |
Yes | Different number of parameters (2 vs 1) |
int print(String s) |
No | Only return type changed |
Output
Click Run to execute your code
Benefits of Overloading
- Readability: Users of your method don't have to remember
different names for the same action (e.g.,
System.out.printlnworks for text, numbers, and booleans!). - Clean Code: Reduces name clutter in your class.
Summary
- Overloading happens when methods have the same name but different parameter lists.
- The parameter list must differ in the number of parameters or the data types of parameters.
- Changing only the return type does not constitute overloading.
Enjoying these tutorials?