A class often needs multiple versions of the same operation that differ only in their inputs. A print() method should work with integers, strings, and booleans. Without overloading, each variant would need a distinct method name (printInt, printString, printBool), making the API inconsistent and hard to remember.
Compile-time Polymorphism (also called Method Overloading) allows multiple methods in the same class to share the same name but have different parameter lists. The compiler determines which version to call based on the number, type, and order of arguments. This decision is made at compile time — hence the name. Overloading improves code readability by using consistent names for logically similar operations.
The compiler uses the method signature (name + parameter types) to select the correct overload. It applies widening conversions, autoboxing, and varargs in that order of preference. If no matching overload is found, a compile error occurs. Overloaded methods can differ in parameter count, parameter types, or both. Return type alone is NOT sufficient for overloading — the compiler needs parameter differences.
- Same name, different parameters: Number, type, or order of parameters must differ
- Compile-time resolution: Which method to call is decided when code is compiled
- Return type alone is insufficient: Methods differing only in return type cause compile error
- Widening preferred over boxing: Java prefers widening (int → double) over autoboxing (int → Integer)
- Varargs is last resort: If no exact match is found, varargs is used as fallback
- Built from: Java Polymorphism — compile-time polymorphism is one of two polymorphism types
- Contrasts with: Runtime Polymorphism — compile-time vs runtime resolution
- Related: Java Methods — overloading is a method-level feature
- Related: Overloading vs Overriding — synthesis comparing the two
- Ambiguous call: If two overloads are equally applicable (e.g.,
method(Integer)andmethod(String)withnull), the compiler reports ambiguity - Widening + boxing chain: Widening followed by boxing is not supported —
intcannot widen then autobox toLong - Varargs ambiguity: Overloading with varargs can create ambiguous calls — the compiler cannot distinguish
method(int...)frommethod(Integer...)withnull