Method Overloading & Resolution Hierarchy
1Concept
Method Overloading is compile-time polymorphism where methods share the same name with different signatures. The Java compiler resolves ambiguous method calls following a strict precedence hierarchy: 1. Exact Primitive Match -> 2. Widening Primitive -> 3. Autoboxing/Unboxing -> 4. Varargs.
2Architecture Diagram
Resolution Precedence: [ Exact Match ] ---> [ Widening (int->long) ] ---> [ Autoboxing (int->Integer) ] ---> [ Varargs (int... args) ]
3Code Example
Core Java
public class OverloadingHierarchyDemo {
static void process(long val) {
System.out.println("Resolved to: Widened primitive (long): " + val);
}
static void process(Integer val) {
System.out.println("Resolved to: Autoboxed (Integer): " + val);
}
static void process(int... vals) {
System.out.println("Resolved to: Varargs (int...)");
}
public static void main(String[] args) {
int testValue = 42;
// Widening beats Autoboxing and Varargs!
process(testValue);
}
}4Expected Output
Resolved to: Widened primitive (long): 42
5Key Takeaways
- ✓Widening beats Autoboxing; Autoboxing beats Varargs.
- ✓Return type alone CANNOT be used to overload methods in Java.
- ✓Compiler rejects ambiguous calls that share equal distance in type hierarchy (e.g. `process(int, long)` vs `process(long, int)`).