BCA / B.Tech 10 min read

Method Overloading in Java

What is Method Overloading in Java?

Method overloading is a feature of object-oriented programming where a class can have multiple methods with the same name, but with different parameter lists. The compiler decides which method to call based on the arguments passed during the method call. This is an example of compile-time polymorphism (or static binding). Overloading makes your code more intuitive and readable by allowing you to use the same name for similar operations on different types of data.

Methods can be overloaded in three ways:
  1. By changing the number of parameters.
  2. By changing the data type of parameters.
  3. By changing the sequence of data types of parameters.

Important: Overloading cannot be achieved just by changing the return type of the method. The method signature (name and parameter list) must be different.


Example of Method Overloading:

class Display {
    // 1. Overloading by changing data type
    public void show(String name) {
        System.out.println("Displaying name: " + name);
    }
    public void show(int number) {
        System.out.println("Displaying number: " + number);
    }

    // 2. Overloading by changing number of parameters
    public void show(String name, int age) {
        System.out.println("Displaying user: " + name + ", Age: " + age);
    }
    
    // 3. Overloading by changing sequence of parameters
    public void show(int age, String name) {
        System.out.println("Displaying Age: " + age + ", User: " + name);
    }
}

public class Main {
    public static void main(String[] args) {
        Display d = new Display();
        d.show("Alice");           // Calls the first method
        d.show(123);               // Calls the second method
        d.show("Bob", 30);       // Calls the third method
        d.show(40, "Charlie");   // Calls the fourth method
    }
}