java


Method Overloading in Java – Write Smarter, Cleaner Code

In Java, you can define multiple methods with the same name but different parameters in the same class. This concept is called method overloading. It’s one of the ways Java supports polymorphism (specifically, compile-time polymorphism).

What is Method Overloading?

Method overloading happens when:

The methods have the same name.

They differ in number of parameters, type of parameters, or both.

The return type can be different, but it alone cannot be used to distinguish overloaded methods.

πŸ’‘ Key point: The compiler decides which method to call based on the method signature (name + parameter list).

Why Use Method Overloading?

Improves code readability.

Allows methods to handle different data types.

Avoids writing different method names for similar operations.

Makes code flexible and easier to maintain. 

Example of Method Overloading

public class Calculator {

    // Method with two int parameters
    public int add(int a, int b) {
        return a + b;
    }

    // Method with three int parameters
    public int add(int a, int b, int c) {
        return a + b + c;
    }

    // Method with two double parameters
    public double add(double a, double b) {
        return a + b;
    }

    public static void main(String[] args) {
        Calculator calc = new Calculator();

        System.out.println("Sum of 2 ints: " + calc.add(5, 10));
        System.out.println("Sum of 3 ints: " + calc.add(5, 10, 15));
        System.out.println("Sum of 2 doubles: " + calc.add(5.5, 4.5));
    }
}
 

Rules for Method Overloading


Parameter list must be different (number or type).

Methods can have different return types but that alone is not enough for overloading.

Overloaded methods can have different access modifiers.

They can throw different exceptions. 

Parameter List Must Be Different

The most important rule:
Overloaded methods must have a different parameter list (also called the method signature).

βœ… Example:
void display(int a) { }
void display(String b) { }
void display(int a, String b) { }


❌ Not Allowed (same parameters):

void display(int a) { }
void display(int x) { } // Compile-time error