DEV Community

Nanthini Ammu
Nanthini Ammu

Posted on

Method Overloading in JAVA - Compile-time Polymorphism

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 Polymorphism (also called Static Polymorphism).
  • The compiler determines which method to call based on the arguments provided.
  • Overloading works within the same class or in subclasses

Rules for Method Overloading :

  • Number of parameters.
  • Type of parameters.
  • Order of parameters.
  • You cannot overload by changing only return type.

Change the Number of parameters :

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

Enter fullscreen mode Exit fullscreen mode

Change the Type of parameters :

class Display {
    void show(int a) {
        System.out.println("Integer: " + a);
    }
    void show(String s) {
        System.out.println("String: " + s);
    }
}

Enter fullscreen mode Exit fullscreen mode

Change the Order of parameters :

class Example {
    void print(int a, String b) { }
    void print(String b, int a) { }
}

Enter fullscreen mode Exit fullscreen mode

Invalid Overloading (Only Return Type Changed)

class Test {

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

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

Compiler error because parameters are the same.


Enter fullscreen mode Exit fullscreen mode
Feature Overloading Overriding
Polymorphism Type Compile-time Runtime
Same Method Name Yes Yes
Parameters Must be different Must be same
Inheritance Required No Yes

Top comments (0)