Lesson · Methods
Overloading and overriding: compile-time and runtime dispatch
18 min readMethod Overloading
Overloads share a name and are resolved by the compiler in three phases. Overrides share a signature and are picked by the JVM from the receiver's runtime class. Same shape of question, opposite moments of decision.
Overloading: one name, several parameter lists
Overloading gives one name several parameter lists: print(int), print(String), print(Object). Callers keep a natural name, the class carries the variants, and every call site is resolved by the compiler while compiling, from the types written in the source.
The legal set has precise edges. Overloads must differ in their parameter lists; return type alone is not enough, because the signature (name plus parameter types) would be identical. Erasure applies too, so f(List<String>) and f(List<Integer>) reduce to the same signature and cannot coexist. Overloads may also spread across a hierarchy, which is where the subtler behaviour lives.
One fact powers everything below: resolution uses the static types at the call, never the values that show up at runtime.
The three phases of overload resolution
When several overloads could accept the same arguments, the compiler evaluates them in three phases, in order, and stops at the first phase that finds an applicable match. A phase-one candidate always beats a phase-two candidate, and varargs only ever compete as a last resort.
The phases are additive: phase two permits everything phase one does, plus boxing and unboxing, and phase three adds varargs on top of both.
| Phase | Permitted conversions | Priority |
|---|---|---|
| Phase 1, strict invocation | Identity, primitive widening, reference widening | First |
| Phase 2, loose invocation | Phase 1 plus boxing and unboxing | Second |
| Phase 3, variable arity | Phase 2 plus varargs | Last resort |
- Phase 1, strict: identity (
int → int), primitive widening (int → long → float → double), reference widening (Integer → Number → Object). Boxing and unboxing are not permitted here. - Phase 2, loose: adds boxing (
int → Integer), unboxing (Integer → int), and chains such asint → Integer → Object(boxing followed by reference widening). - Phase 3, variable arity: considers methods declared with varargs (
...), which is why a fixed-arity overload always outranks its varargs twin.
The compiler stops at the first phase with an applicable method. It does not continue to later phases hoping to find a more specific match. Every worked example below is this one rule wearing different arguments.
Overload lab
pick a callAn int widens to long in phase one. Boxing only arrives in phase two, which a phase-one match stops before reaching.
Widening before boxing before varargs: the phases stop at the first with an applicable match.
Which method wins within a phase
A phase may leave more than one applicable method, and then the most specific method wins. The working definition: a method that accepts a narrower type beats one that accepts a broader type. The precise relation lives in the JLS; tighter wins covers every case in this lesson.
A worked example. Two overloads, f(Object) and f(Integer), and the call f(10):
f(Object)is applicable through boxing (int → Integer) followed by reference widening (Integer → Object).f(Integer)is applicable through boxing alone (int → Integer).- Both are considered in phase 2, because phase 1 found nothing without boxing.
Integeris more specific thanObject, sof(Integer)is selected and the program printsInteger.
Narrower beats broader, within one phase. Specificity never pulls a method out of a later phase: the phases decide which methods are even in the room. Add an f(long) overload and it wins before either of these, because widening runs in phase 1 and phase 2 is never reached.
When the candidate types are unrelated
Specificity can only rank types that are related by subtyping. When two applicable candidates come from unrelated types, there is no most specific method, and the compiler reports an ambiguous method invocation error instead of guessing.
The classic trigger is the null literal. With both f(String) and f(Integer) in scope, every candidate accepts null, and neither type is a subtype of the other:
f(String)is applicable:nullis assignable to String.f(Integer)is applicable:nullis assignable to Integer.- Neither is more specific than the other, so the call
f(null)fails to compile.
A cast fixes the static type before resolution runs: f((String) null) calls the String overload, f((Integer) null) the Integer one. Note the companion case: when the candidates are related, such as f(Object) and f(Integer), the tighter one simply wins, so a null argument is not automatically an ambiguity.
Conversions do not arbitrarily chain
Method invocation conversions are permitted in specific combinations, never in arbitrary chains. The table below is the working map.
| Conversion | Allowed? | Example |
|---|---|---|
| Primitive widening | Yes | int → long |
| Boxing | Yes | int → Integer |
| Unboxing plus primitive widening | Yes, phase 2 | Integer → int → long |
| Boxing plus reference widening | Yes, phase 2 | int → Integer → Object |
| Widening then boxing | No | int → long → Long |
| Boxing to a different wrapper | No | int → Long |
Both prohibitions share one reason: an int boxes to an Integer, and there is no int → Long conversion at all, because that would require widening and boxing, or boxing and reference widening, in a single step. So f(Object) does accept an int (int → Integer → Object, permitted in phase 2), while a f(Long) overload never matches one. That prohibition explains a whole family of otherwise cryptic compile errors.
The traps that survive code review
Three situations decide overload calls in ways reviewers miss:
list.remove(1)versuslist.remove(Integer.valueOf(1)): two overloads of one method, remove by index and remove by value. An int argument picks the index version; the boxed value picks the object version. Both compile, and they do entirely different things.- A parameter-list change meant as an override: the parent method survives, the new one is an overload, and every existing caller keeps the old behaviour.
@Overrideis the guard that catches it. - An overload added later in a subclass: through a reference typed as the parent, calls keep binding to the older method, because resolution only sees what the static type exposes. The new variant is not lost; it is invisible through that reference.
Overloads across a hierarchy: the static-type rule
Inherited overloads join the candidate set, but which candidates are visible depends on the type of the reference used at the call. Child c = new Child(); c.f("text") sees both the inherited f(Object) and the new f(String), and picks the tighter one. Parent p = new Child(); p.f("text") sees only the parent's members, so it binds to f(Object), even though the object is a Child.
An overload that only exists in the subclass is not callable through the parent reference at all. That asymmetry is why overloading across a hierarchy is a smell: if a subclass needs a variant of a parent method, a distinct name or a plain override reads better, and neither can go silently unreachable.
Overriding: same signature, decided from the receiver
An override repeats the parent's signature: same name, same parameter types after erasure. It may narrow the return type (a covariant return, String label() overriding Object label()), it may not reduce visibility, and it may not throw broader checked exceptions. @Override makes the compiler verify the whole list, and it is not decoration: write it every time.
The call compiles against the static type of the receiver (the object the call is sent to, here a), so the method must exist on the declared type for the line to compile at all. At runtime the JVM looks at the receiver's actual class and walks up the hierarchy to the first declaration of the signature. That is why Animal a = new Dog(); a.speak() runs Dog's code: the dispatch reads the object, not the variable.
Two neighbours of overriding behave differently, and the inheritance chapter takes them up in full: a static method is selected from the declared type of the reference at compile time (hiding, never overriding), and a field access reads the field declared by the static type, because fields are not polymorphic at all.
Dispatch stepper · one object, four calls
Animal a = new Dog();
a.speak();
a.stat();
process(a);
Dog overrides speak and label; both declare stat. The class also holds process(Animal) and process(Dog).
a: static Animal, runtime Dog
Both facts will matter, in different moments.
One line, two types. The variable a has static type Animal, the only type the compiler knows. The object it points at is a Dog, the class that exists at runtime.
The contrast, in one sentence and one list
Overloads are chosen from the types written in the source; overrides are chosen from the object that shows up at the call.
- Overloading: one name, different parameter lists, decided by the compiler, uses static types, stops at the first phase with an applicable match.
- Overriding: one signature, a subclass implementation, decided at the call by the JVM, uses the receiver's runtime class, walks the hierarchy to the first match.
- One class can exercise both:
String.valueOf(1)andString.valueOf(true)are overloads of one method;toString()in your own classes is an override of Object's. - Interview shorthand: overloading is static and local, overriding is dynamic and hierarchical.
The interview playbook
When an overload question lands in an interview or a certification exam, run the same sequence every time:
- Check phase 1: identity or widening only. Any applicable method here wins outright.
- Phase 2 only if phase 1 found nothing: add boxing and unboxing to the candidate set.
- Phase 3 last: varargs compete only when the first two phases produced nothing.
- Within the earliest matching phase, pick the most specific applicable method.
- If no unique most specific method exists, the call does not compile; a cast at the call site fixes it.
- Do not assume conversions chain: check the allowed combinations table before predicting a winner.
First applicable phase wins. Within that phase, the most specific applicable method wins. If there is no unique most specific method, compilation fails. That sentence plus the tables above answers every question this lesson covers.
Annotate every override, it is not decoration
Change a parameter type while meaning to override and you have written an overload: the parent method survives, your version is never dispatched to, and every caller keeps the old behaviour. @Override makes the compiler check the intent and turns that silent bug into a build failure. It also catches name typos, which are the same bug in different clothes.
Interview angles
How are overloads resolved?+
In three phases, stopping at the first with an applicable match: strict invocation (identity, primitive widening, reference widening), then boxing and unboxing, then varargs. Within a phase the most specific method wins, and a tie between unrelated types is a compile error rather than a guess.
Why does f(long) beat f(Integer) for an int argument?+
Widening to long is already legal in phase one; reaching Integer needs boxing, which only arrives in phase two. The compiler stops at the first phase with a match, so widening always outranks boxing.
What does f(null) choose between f(Integer) and f(Object)?+
f(Integer): both accept the null literal, and Integer is the more specific type. Ambiguity appears only between unrelated candidates, such as f(String) and f(Integer) together, and a cast in the call resolves it.
Overloading versus overriding in one breath?+
Overloading: same name, different parameter lists, resolved by the compiler from the static types at the call site. Overriding: same signature, subclass implementation, resolved by the JVM from the receiver's runtime class. @Override proves the second was intended.
Can an override narrow the return type?+
Yes: a covariant return is legal, so String label() may override Object label(). Parameter types, by contrast, must match exactly; changing one creates an overload instead.