EMZETT.
Login

Overloading

In short: Several methods with the same name but a different parameter list (number or type) — Java automatically picks the matching variant on a call.

In more detail: The return type alone isn’t enough to distinguish two methods — only the number/type of parameters count for overloading. Not to be confused with overriding (re-implementing a superclass’s method in a subclass) — that’s a different concept from Inheritance.

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

In Depth

class Calculator {
    int sum(int a, int b) { return a + b; }
    double sum(double a, double b) { return a + b; }
    int sum(int a, int b, int c) { return a + b + c; } // differs by count
    String sum(String a, String b) { return a + b; }    // differs by type
}
 
Calculator c = new Calculator();
c.sum(1, 2);          // calls the (int, int) variant
c.sum(1.5, 2.5);      // calls the (double, double) variant
c.sum(1, 2, 3);       // calls the (int, int, int) variant
c.sum("A", "B");      // calls the (String, String) variant
 
// int sum(int x, int y) { ... } // would NOT compile - only the return type
// would differ from the first sum(int,int), which isn't enough

The compiler decides at compile time (not only at runtime) which overloaded variant matches a specific call — based solely on the number and type of the arguments passed. If the argument types don’t match exactly, but there’s a compatible implicit conversion (e.g. int to double), Java picks the “closest” matching overload. Important: overloading is a purely compile-time concept, while overriding (re-implementing a superclass’s method in a subclass, see Inheritance) is only decided at runtime based on the actual object type — both sound similar, but solve different problems.

See also: Methods, Parameters, Constructors