Null value in the method parameter

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 the following output in the console

 List of Object 

Why does this call not call test(Object a) ? Can you explain how this took List as null ?

+6
source share
2 answers

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

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

The exact algorithm used by Java to overload overloaded methods is quite complex. See Section 15.12.2.5 for details .

+7
source

Always in the first place, in such cases. If you change List to String, it will print the same. Each class is a child of the object, so if it should be overloaded, it belongs to a more specific class.

+4
source

Source: https://habr.com/ru/post/986833/


All Articles