Java Method Overloading
Method overloading in Java allows you to have multiple methods with the same name in the same class, as long as their parameter lists are different. It's a way to achieve polymorphism and enhance code readability.
1. Why Use Method Overloading?
Overloading methods improves code clarity by allowing the same method name to perform similar tasks on different data types or different numbers of parameters.
2. Rules for Method Overloading
To overload methods, you must change one of the following:
- Number of parameters
- Data types of parameters
- Order of parameters (if data types are different)
3. Examples
3.1 Different Number of Parameters
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
}
3.2 Different Data Types
public class Display {
public void print(String message) {
System.out.println(message);
}
public void print(int number) {
System.out.println(number);
}
}
4. Key Takeaways
- Method overloading allows multiple methods with the same name but different parameters.
- It enhances code readability and reusability.
- Overloaded methods can have different return types, but return type alone is not sufficient for overloading.
- Be cautious to avoid confusion when overloading methods.