Today we discuss about the method overloading,
WHAT :
Method overloading is a feature in Java where multiple methods share the same name but differ in their parameter list. The difference can be in the number of parameters, data types, or order of parameters.Java decides which method to call at compile time.
EXAMPLE :
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(10, 20));
System.out.println(c.add(5.5, 2.5));
System.out.println(c.add(1, 2, 3));
}
}
WHY:
Many beginners think the method overloading changing the return type or same logic again with different names,it is very wrong .Because the it exists to make a code cleaner ,reusable and easier to understand while handling different inputs for the same operation.
❌ Changing Only the Return Type:
int add(int a, int b)
double add(int a, int b)
Top comments (0)