Memra

Method overloading & overload resolution

◈ 3 cards

Same name, different parameter lists — and how the compiler chooses the winner.

Overloading: one name, many signatures

Two methods in the same class may share a name as long as their parameter lists differ (in number, type, or order of parameters). The return type alone is not enough — that is a compile error:

static void print(int n)    { System.out.println(n); }
static void print(String s) { System.out.println(s); }
static void print(int a, int b) { System.out.println(a + ", " + b); }

The compiler selects the most specific applicable overload using a three-phase lookup:

  1. Exact match — no conversion. Always preferred.
  2. Widening primitive conversion — e.g. byteint, intlong.
  3. Autoboxing / unboxing — e.g. intInteger.
  4. Varargs — considered last.

Phase 1 always wins over phase 2, which wins over phase 3, which wins over phase 4. If two overloads are equally specific at the same phase, the compiler reports an ambiguity error rather than picking arbitrarily.

nothing appliesnothing appliesnothing applies1 — exact matchno conversion at all2 — wideningbyte to int, int to long3 — autoboxingint to Integer4 — varargsconsidered last
A phase is only reached when no candidate applied in the phase above, which is why widening always beats autoboxing and varargs never wins while anything else fits.
the callwhat the compiler seesoutcomeprint(42)print(int) — exactcompilesprint(null)String or Object?ambiguity errorprint((String) null)print(String)compiles
null is assignable to every reference type, so neither print(String) nor print(Object) is the more specific candidate. The cast states which one you meant.
NORMAL ~/memra/learn/java-from-zero/method-overloading utf-8 LF