Method Overloading in Java

A core concept of Object-Oriented Programming & Compile-Time Polymorphism

What is Method Overloading?

Method Overloading allows a class to have multiple methods with the same name but different parameter lists. It is an example of Compile-Time (or Static) Polymorphism.

Key Rules:
  • Methods must share the exact same method name.
  • Methods must differ in parameter list (number, type, or order of parameters).
  • Method overloading cannot be achieved solely by changing the return type.

Ways to Achieve Method Overloading

1. Changing the Number of Parameters

Overloading by providing a different count of arguments in method definitions.

class Product {
    // Multiplying two integer values
    public int multiply(int a, int b) {
        return a * b;
    }

    // Multiplying three integer values
    public int multiply(int a, int b, int c) {
        return a * b * c;
    }
}

public class Main {
    public static void main(String[] args) {
        Product ob = new Product();
        System.out.println("Product of 2 numbers: " + ob.multiply(1, 2));
        System.out.println("Product of 3 numbers: " + ob.multiply(1, 2, 3));
    }
}
Output:
Product of 2 numbers: 2
Product of 3 numbers: 6

2. Changing Data Types of Parameters

Overloading by defining methods with different parameter data types.

class Product {
    public int prod(int a, int b, int c) {
        return a * b * c;
    }

    public double prod(double a, double b, double c) {
        return a * b * c;
    }
}

public class Main {
    public static void main(String[] args) {
        Product p = new Product();
        System.out.println(p.prod(1, 2, 3));       // Calls int version
        System.out.println(p.prod(1.0, 2.0, 3.0)); // Calls double version
    }
}
Output:
6
6.0

3. Changing the Sequence/Order of Parameters

Overloading by changing the sequence of parameter data types in the method declaration.

class Student {
    public void studentId(String name, int rollNo) {
        System.out.println("Name: " + name + ", Roll-No: " + rollNo);
    }

    public void studentId(int rollNo, String name) {
        System.out.println("Roll-No: " + rollNo + ", Name: " + name);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student();
        s.studentId("Sweta", 1);
        s.studentId(2, "Gudly");
    }
}
Output:
Name: Sweta, Roll-No: 1
Roll-No: 2, Name: Gudly