1.Method Overloading:
Method Overloading means using the same method name with different parameters in the same class.
In simple words:
Same Method Name
Different Input
Different Behavior
This is called Method Overloading.
Why Do We Use Method Overloading?
Without method overloading, we would write like this:
addTwoNumbers()
addThreeNumbers()
addFourNumbers()
This makes the code messy and hard to maintain.
Instead, we use:
add()
add()
add()
Same method name — cleaner and easier to understand.
Simple Example:
class Student {
void add(int a, int b){
System.out.println(a + b);
}
void add(int a, int b, int c){
System.out.println(a + b + c);
}
public static void main(String[] args){
Student s = new Student();
s.add(10,20);
s.add(10,20,30);
}
}
Output:
30
60
Here:
add(10,20) calls first method
add(10,20,30) calls second method
Same method name, but different parameters.
This is Method Overloading.
Rules for Method Overloading:
Method overloading happens when:
1. Number of Parameters Changes:
- add(int a, int b)
- add(int a, int b, int c)
2. Data Type Changes:
add(int a, int b)
add(double a, double b)
3. Order of Parameters Changes:
add(int a, double b)
add(double a, int b)
Advantages of Method Overloading:
Makes code clean
Easy to read
Easy to maintain
Reduces duplicate method names
Improves code flexibility
Top comments (0)