What are the rules for method overloading in Java?

Method overloading in Java allows multiple methods in the same class to share the same name, provided their parameter lists are different. It is a form of compile-time polymorphism that enables a method to perform similar operations with different types or numbers of inputs.

Key Points: • Overloaded methods must have the same method name. • The parameter list must differ in number, type, or order of parameters. • Changing only the return type does not create a valid overloaded method. • Overloaded methods can have different access modifiers and exception declarations. • Method overloading is resolved by the compiler at compile time.

Rules for Method Overloading:

1. Different Number of Parameters

void display(int a)

void display(int a, int b)

2. Different Parameter Types

void display(int a)

void display(String a)

3. Different Parameter Order

void display(int a, String b)

void display(String b, int a)

Invalid Rule:

Methods cannot be overloaded by changing only the return type.

Example:

int calculate(int a)

double calculate(int a) // Compilation Error

Example: A Calculator class can provide multiple versions of an add() method to handle different input combinations.

Code Example:

class Calculator {

    int add(int a, int b) {
        return a + b;
    }

    int add(int a, int b, int c) {
        return a + b + c;
    }

    double add(double a, double b) {
        return a + b;
    }
}

public class Demo {

    public static void main(String[] args) {

        Calculator calculator = new Calculator();

        System.out.println(calculator.add(10, 20));

        System.out.println(calculator.add(10, 20, 30));

        System.out.println(calculator.add(10.5, 20.5));
    }
}

Output:

30
60
31.0

What Can Be Different in Overloaded Methods?

• Number of parameters • Data types of parameters • Order of parameters • Access modifiers (public, private, protected) • Exception declarations

What Cannot Be the Only Difference?

• Return type • Method body

Benefits of Method Overloading:

• Improves code readability • Reduces the need for multiple method names • Makes APIs easier to use • Supports compile-time polymorphism

Interview Tip: A concise interview answer is:

"Method overloading requires methods to have the same name but different parameter lists. The parameters must differ in number, type, or order. Changing only the return type is not sufficient because Java uses the method signature, not the return type, to distinguish overloaded methods."