8.2 Method Overloading & Overload Resolution Order
Key Takeaways
Overloads have distinct method signatures. Return type, visibility, modifiers, and parameter names do not distinguish two otherwise identical signatures.
Declarations
m(int[])andm(int...)have the same parameter type. They cannot both appear as overloads in one class.The compiler checks strict fixed arity, then loose fixed arity, then variable arity. It selects a most-specific method from the first phase with applicable candidates.
The compiler never performs primitive widening and autoboxing in a single step—passing an
intliteral5tovoid m(Long x)fails to compile.Calling
m(1, 2)whenm(int, long)andm(long, int)exist, orm(null)when unrelatedm(String)andm(Integer)exist, triggers an ambiguous method call compile error.
Method Overloading & Overload Resolution Order
Method overloading occurs when multiple methods in the same class (or inherited into a subclass) share the same name while declaring different parameter lists. Overload resolution is determined entirely at compile time based on the compile-time types of the arguments—not at runtime.
Valid Overloads vs. Illegal Duplicates
Ordinary overloads differ by the number, types, or order of distinct parameter types. Return types, access levels, static, and throws clauses can differ when the declarations are otherwise legal. A difference erased by the compiler cannot create an overload, so m(List<String>) and m(List<Integer>) clash.
public class Calculator {
public int add(int a, int b) { return a + b; }
protected double add(double a, double b) { return a + b; } // Valid: different types
public static int add(int a, int b, int c) { return a + b + c; } // Valid: different count
public String add(String s, int n) { return s + n; }
public String add(int n, String s) { return n + s; } // Valid: different order
}
Changing anything outside the parameter types—such as return type, visibility, static, parameter names, or checked exceptions—does not create an overload and fails compilation with method ... is already defined:
| Pair of Declarations in Same Class | Outcome | Reason |
|---|---|---|
int run(int x) and long run(int x) | Compile Error | Differ only by return type |
public void go(int a) and private void go(int b) | Compile Error | Differ only by access modifier & parameter name |
void log(String s) and static void log(String s) | Compile Error | Differ only by static modifier |
void push(int[] a) and void push(int... a) | Compile Error | Identical array parameter signature under the hood |
void push(int[] a) and void push(long... a) | Compiles | Different element types (int[] vs long[]) |
Important
Watch closely for int[] vs. int... in the same class! Because int... is syntactic sugar for int[], declaring both void sum(int[] nums) and void sum(int... nums) is a compile-time duplicate method error.
The Three Phases of Overload Resolution
Java SE 8 uses three applicability phases. In each phase, the compiler checks the whole argument list:
- Strict fixed arity. Match with identity or permitted widening conversions. Boxing and unboxing are not used.
- Loose fixed arity. Also allow boxing, optionally followed by reference widening, or unboxing, optionally followed by primitive widening.
- Variable arity. Match the trailing arguments against the varargs element type and package them into an array.
Stop at the first phase with applicable candidates. Resolve specificity within that phase. If the ordinary candidates are ambiguous, adding a later-phase candidate cannot rescue the call. A varargs declaration can also participate in a fixed-arity phase if the supplied argument matches its array type.
public class OverloadOrder {
static void test(int x) { System.out.println("int"); }
static void test(long x) { System.out.println("long"); }
static void test(Integer x) { System.out.println("Integer"); }
static void test(Object x) { System.out.println("Object"); }
static void test(int... x) { System.out.println("int array"); }
public static void main(String[] args) {
test(42); // int: most specific in strict fixed arity
test(new int[]{42}); // int array: fixed-arity use of the varargs declaration
}
}
Remove test(int) and the strict phase selects test(long). Remove test(long) as well and the loose phase selects test(Integer), which is more specific than test(Object). If both reference and primitive fixed-arity candidates are removed, the scalar call uses the varargs array. Contrast test(Integer.valueOf(42)): with only test(int) and test(Object) available, the reference-widening conversion to Object is applicable in the strict phase, before unboxing to int.
The Forbidden Conversion: Never Widen + Box in One Step
Java allows boxing followed by reference widening (int -> Integer -> Number -> Object), because Integer is-a Number and Object. However, Java forbids primitive widening followed by autoboxing in a single conversion:
public class WidenBoxTrap {
static void accept(Long x) { System.out.println("Long"); }
static void accept(Number x) { System.out.println("Number"); }
public static void main(String[] args) {
int v = 5;
accept(v); // Boxes int -> Integer, then widens Integer -> Number! Prints: Number
}
}
Remove accept(Number x) so only accept(Long x) remains, and accept(5) fails to compile: Java will not widen int to long and then box long to Long automatically. You would need an explicit 5L or (long) v. By the same rule, passing a byte to void take(Integer i) fails compilation because byte autoboxes only to Byte, never to Integer.
Ambiguous Method Calls
The first successful applicability phase can have competing methods. For the distinct signatures below, the call is ambiguous when there is no most-specific choice:
1. Cross-Widening Ambiguity
public class AmbiguousNumbers {
static void calc(int a, long b) { System.out.println("int, long"); }
static void calc(long a, int b) { System.out.println("long, int"); }
public static void main(String[] args) {
calc(1L, 2); // Unambiguous: exact match (long, int)
// calc(1, 2); // COMPILE ERROR: reference to calc is ambiguous!
}
}
For calc(1, 2), the first overload widens argument 2 (int -> long) while the second widens argument 1 (int -> long). Neither parameter list is uniformly more specific, so the compiler rejects the call.
2. null Literal Ambiguity
Passing null matches any reference type, so the compiler picks the most specific subtype—if one exists:
public class NullOverload {
static void show(Object o) { System.out.println("Object"); }
static void show(String s) { System.out.println("String"); }
static void pick(String s) { System.out.println("String"); }
static void pick(Integer i) { System.out.println("Integer"); }
public static void main(String[] args) {
show(null); // Compiles! Prints "String" (String is subtype of Object)
// pick(null); // COMPILE ERROR: String and Integer are unrelated siblings!
}
}
3. Varargs & List.remove Traps
If you declare both void m(int... a) and void m(Integer... a) and call m(1, 2), compilation fails as ambiguous because both are applicable in the variable-arity phase and neither is more specific for that call. Similarly, keep in mind the classic ArrayList<Integer> trap: calling list.remove(1) invokes remove(int index) (strict fixed arity for int), not remove(Object o)—to remove the value 1, you must pass Integer.valueOf(1).
Which pair cannot have both declarations in the same class, assuming legal bodies for the stated return types?
void log(String s, int n) and static String log(int n, String s)
void log(int[] values) and void log(long... values)
void log(int[] values) and protected int log(int... values)
void log(Number n) and void log(Double d)
Given the overloads below, what is the output of calling route((byte) 7)?
static void route(short s) { System.out.print("short "); }
static void route(Byte b) { System.out.print("Byte "); }
static void route(int... a) { System.out.print("varargs "); }
short
Byte
varargs
Compilation fails because the call is ambiguous
Which method call fails to compile if inserted in a static method of the following class?
public class DispatchCheck {
static void go(long x) { System.out.println("long"); }
static void go(String s) { System.out.println("String"); }
static void go(Object o) { System.out.println("Object"); }
static void duo(int a, long b) {}
static void duo(long a, int b) {}
}
go(null);
go(5L);
duo(5L, 6);
duo(5, 6);
Sections you finish are checked off in the contents.