EMZETT.
Login

Overloading (Method Overloading)

In short: Several methods with the same name but a different parameter list (number or type of parameters) within the same class.

In more detail: Which of the overloaded variants is actually executed on a call is decided by the compiler based on the arguments passed — e.g. an add(int, int) and an add(double, double) method side by side. Not to be confused with overriding (method overriding), where a subclass re-implements an inherited method with an identical signature (see Inheritance).

In Depth

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;
    }
}

All three methods are called add, but differ in their signature — the combination of the number AND types of the parameters (the return type alone does NOT count as a distinguishing feature in most languages, so two methods with identical parameters but different return types would still be a conflict). On the call add(2, 3), the compiler automatically picks the matching variant based on the arguments passed — this process is called “overload resolution”.

Overloading is often used to conveniently offer the same basic operation for different input forms, without having to invent a separate, differently named method name for every variant (addTwoInts, addTwoDoubles, …) — the caller only has to remember ONE name, the compiler takes care of selecting the right implementation.

Important distinction from overriding: overloading happens within the same class with different signatures and is resolved at compile time. Overriding, by contrast, happens between a superclass and a subclass with an IDENTICAL signature — the subclass replaces the inherited implementation with its own, which is only decided at runtime based on the actual object type (see Polymorphism). Both terms sound similar, but refer to fundamentally different mechanisms.

See also: Methods, Parameters, Inheritance