6

I have the following code

import java.util.List;

public class Sample {

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

    static void test(List<Object> a){
        System.out.println("List of Object");
    }
    static void test(Object a){
        System.out.println("Object");
    }
}

and I got following output in console

List of Object

Why doesn't this call test(Object a)? Can you some one explain how it took "List as" null?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Kannan Thangadurai
  • 1,117
  • 2
  • 17
  • 36
  • 2
    Related: [Overloaded method selection based on the parameter's real type](http://stackoverflow.com/q/1572322/1065197), [Method overloading and choosing the most specific type](http://stackoverflow.com/q/9361639/1065197). – Luiggi Mendoza May 08 '15 at 15:26

2 Answers2

7

In a nutshell, the most specific method among the overloads is chosen.

In this case the most specific method is the one that takes List<Object> since it's a subtype of Object.

The exact algorithm Java uses to pick overloaded methods is quite complex. See Java Language Specification section 15.12.2.5 for details.

aioobe
  • 413,195
  • 112
  • 811
  • 826
4

Always specific first, in cases like that. If you change List to String, it will print the same thing. Every class is child of Object, so if it have to overload, will be to the more specific class.

Raphael Amoedo
  • 4,233
  • 4
  • 28
  • 37