Why can null be passed to an overloaded Java method?

I found this Java code from this site . I don’t understand how it compiles without an ambiguous error.

package swain.test; public class Test { public static void JavaTest(Object obj) { System.out.println("Object"); } public static void JavaTest(String arg) { System.out.println("String"); } public static void main(String[] args) { JavaTest(null); } } 

Output:

 String 
+6
source share
1 answer

null can be passed as JavaTest(String arg) , and JavaTest(Object obj) , so the compiler chooses a method with more specific types of arguments. Since String more specific than Object ( String is a subclass of Object ), JavaTest(String arg) is selected.

If you had JavaTest(Integer obj) instead of JavaTest(Object obj) , the compilation would fail, because Integer no more specific than String and String is not more specific than Integer`, so the compiler will not be able to make a choice.

+6
source

All Articles