Method Overloading means defining multiple methods in the same class with the same name but different parameters (type, number or order).

Example

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

Ways to overload

  • Different number of arguments: add(int, int) vs add(int, int, int)
  • Different types of arguments: add(int, int) vs add(double, double)
  • Different order: print(String, int) vs print(int, String)

Features

  • Happens at compile-time β†’ Also called compile-time polymorphism.
  • Improves readability and flexibility.
  • Works only in the same class (or inherited class).
  • Can overload:
    • instance methods,
    • constructors,
    • static methods.

Comparison

Overloading vs Overriding

FeatureOverloadingOverriding
Occurs InSame classSubclass (inheritance)
ParamsMust be differentMust be same
Return TypeCan differMust be same (or covariant)
Polymorphism TypeCompile-timeRuntime

Tip

If methods have the same name but different parameters, it’s overloading.
Changing only the return type won’t work - the compiler will complain.


Parent: _OOP Concepts