0

Which overloaded method will be called for the below method and why?

I executed this code and it calls the overloaded method with List but why does it happen?

public class AmbigiousOverload {

    public static void add(Object o) {
        System.out.println("Overloaded method with Object.");
    }

    public static void add(List l) {
        System.out.println("Overloaded method with List.");
    }

    public static void main(String[] args) {
        add(null);
    }

}

Output: Overloaded method with List.

1 Answers1

1

The List overload is called because the List overload is the most specific matching overload, as all List implementations are subclasses of Object.

From JLS Sec 15.12.2.5:

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error.

Since any parameter you can pass to add(List) can also be passed to add(Object), add(List) is more specific. As such, given that null can be passed to both, the more specific method is the one chosen.

Note that it wouldn't compile if you had an add(String) overload, since List and String are "equally" specific. (Or any other class: it doesn't have to be String).

Andy Turner
  • 137,514
  • 11
  • 162
  • 243