DEV Community

Cover image for What is Method overloading and why it is needed?(for beginners)
Arul .A
Arul .A

Posted on

What is Method overloading and why it is needed?(for beginners)

  Today we discuss about the method overloading,
Enter fullscreen mode Exit fullscreen mode

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));
    }
}

Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

❌ Changing Only the Return Type:

int add(int a, int b)
double add(int a, int b)

Enter fullscreen mode Exit fullscreen mode

Top comments (0)