Method overloading
Перегрузка методов
A class can offer several versions of a method under the same name, each with a different parameter list. In Java, the compiler uses the arguments in a call to decide which version to use.
Also known as: overriding, переопределение
One operation, several ways to call it
A search method might accept just a query or take both a query and a result limit. Both versions can be called search because they represent the same operation. Each version is an overload. The method declaration lists its parameters; the caller supplies arguments for those parameters.
How overload resolution works
In Java, overloads can differ in the number, types, or order of their parameters. For example, search(String, int) and search(int, String) have different signatures. Renaming a parameter does not create a new overload, and neither does changing only the return type.
At compile time, Java checks which visible overloads can accept the arguments. It starts with stricter matching rules and considers options such as boxing a primitive or packing arguments into a variable-length argument list only in later phases. Among the applicable methods in the first phase that finds a match, the compiler looks for a most specific candidate. If it cannot find an applicable method or resolve the choice, the call fails to compile.
Example: a default value in an API
class Prices {
static int total(int unitPrice) {
return total(unitPrice, 1);
}
static int total(int unitPrice, int quantity) {
return unitPrice * quantity;
}
}
// In a caller:
Prices.total(12); // 12
Prices.total(12, 3); // 36
The one-argument overload handles the common case by passing a quantity of 1 to the other overload. The calculation lives in one place. This pattern is useful when callers need different levels of control over the same operation. If two variants do different things or have different side effects, distinct names usually make the API easier to read.
Overloading is not overriding
Overloading answers “Which signature does this call select?” Overriding answers “Which implementation of that signature runs?” A Java subclass can override an inherited instance method by providing its own implementation of that method. A single call can involve both mechanisms: the compiler selects the overload, then runtime dispatch uses the receiver object's actual class to choose the implementation of the selected instance method.
What to expect in an interview
Given print(Object) and print(String), what does print(value) select after Object value = "hello";? It selects print(Object) because the argument expression has compile-time type Object. The fact that it holds a string does not change the selected overload. For an ambiguity check, suppose the only overloads are print(String) and print(Integer). The call print(null) fits both, and neither parameter type is more specific than the other, so Java reports a compile-time error.