✅ Key Rules of Method Overloading:
- Same method name
- Different parameter list
- Different number of parameters
- Different types of parameters
-
Different order of parameters
Return type can be different, but not enough by itself to overload a method.
🔧 Example of Method Overloading:
`public class Calculator {
// Method with 2 int parameters
public int add(int a, int b) {
return a + b;
}
// Method with 3 int parameters
public int add(int a, int b, int c) {
return a + b + c;
}
// Method with 2 double parameters
public double add(double a, double b) {
return a + b;
}
// Method with int and double (different order)
public double add(int a, double b) {
return a + b;
}
public double add(double a, int b) {
return a + b;
}
}
`
⚠️ Not Valid Overloading:
// This will cause a compile-time error
public int add(int a, int b) { ... }
public double add(int a, int b) { ... } // ❌ Only return type is different
> 💡 Why use method overloading?
- Improves code readability and reusability
- Makes code more intuitive (e.g., one method name for similar actions)
- Helps handle different types or numbers of inputs in a clean way 🎯 Use of Method Overloading in Java
Method overloading is used to increase the readability, flexibility, and usability of your code. Here’s why it’s useful:
✅ 1. Improves Code Readability and Clarity
Instead of creating multiple methods with different names for similar actions, you can use the same method name with different parameters.
Without Overloading:
void drawCircle() {}
void drawRectangle() {}
void drawTriangle() {}
With Overloading:
void draw() {} // draw something
void draw(int radius) {} // draw a circle
void draw(int length, int breadth) {} // draw a rectangle
✅ 2. Better Code Reusability
Same method name can be reused for multiple variations of the same operation. You don’t have to invent new names for every small variation.
✅ 3. Helps in Creating Flexible APIs
Java libraries (like System.out.println) use method overloading to allow multiple types of arguments.
System.out.println("Hello");
System.out.println(123);
System.out.println(3.14);
All these calls go to different overloaded versions of println().
✅ 4. Supports Compile-Time Polymorphism
Method overloading is one way Java achieves polymorphism—the ability to use the same interface for different data types.
✅ 5. Makes Constructor Overloading Possible
You can define multiple constructors with different arguments to allow objects to be created in different ways.
class Person {
Person() {}
Person(String name) {}
Person(String name, int age) {}
}
🤖 Real-world Analogy:
Think of method overloading like calling a contact named "Mom" on your phone:
- If you say “Call Mom,” it might dial her mobile.
- “Call Mom at work” dials her office.
- “Call Mom on WhatsApp” uses another method.