Benefits of Method Overloading

java dev.to

What is a Method:

A method is a block of code that performs a specific task. The code inside the method executes only when the method is called.
Enter fullscreen mode Exit fullscreen mode

Syntax:

returnType methodName(parameters) {
    // code
}
Enter fullscreen mode Exit fullscreen mode

Example:

public class Demo {

    void greet() {
        System.out.println("Hello Bala");
    }

    public static void main(String[] args) {

        Demo obj = new Demo();
        obj.greet();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Hello Bala
Enter fullscreen mode Exit fullscreen mode

Why Use Methods?

Code Reusability
Reduces Code Duplication
Easy Maintenance
Better Readability

What is Method Overloading:

Method Overloading means creating multiple methods with the same name in the same class but with different parameters.

The parameters can differ by:

Number of parameters.
Type of parameters.
Order of parameters.

Example:

public class CalculatorOverloading {

    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) {

        CalculatorOverloading obj =
            new CalculatorOverloading();

        obj.add(10, 20);
        obj.add(10, 20, 30);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

30
60
Enter fullscreen mode Exit fullscreen mode

How It Works?

obj.add(10,20)

Compiler calls:
add(int,int)

obj.add(10,20,30)

Compiler calls:
add(int,int,int)

Why Use Method Overloading?

It allows us to use the same method name for performing similar operations.

It improves code readability and makes the program easier to understand.

It helps achieve Compile-Time Polymorphism in Java.

Source: dev.to

arrow_back Back to Tutorials