Java overload concept

When I run this code, it prints a String . My question is why there is no compile-time error? The default value of the object, as well as String, is null. Then why does the compiler not say Reference to method1 is ambiguous .

 public class Test11 { public static void method1(Object obj) { System.out.println("Object"); } public static void method1(String str) { System.out.println("String"); } public static void main(String[] arr ) { method1(null); } } 
+6
source share
4 answers

From this answer :

There you will notice that this is a compile-time task. JLS says in subsection 15.12.2:

This step uses the method name and argument expression types to find available and applicable method methods. There may be more than one such method, in which case the most specific one is chosen .

+3
source

The compiler will consider all possible overloads of the method, which may correspond to the parameters that you pass. If one of them is more specific than all the others, then it will be chosen, it will be considered ambiguous, if there is no single most specific overload.

In your example, there are two possible overloads, method1(Object) and method1(String) . Since String more specific than Object , there will be no ambiguity, and the String parameter will be selected. If there was a third overload, such as method1(Integer) , then there is no longer much choice for calling method1(null) , and the compiler will generate an error.

+3
source

Good in one sentence

In the case of overloaded methods, the compiler selects the method with the most specific type, since String is the most specific type of the compiler. Object calls the method that takes a string as an argument

0
source
 public class Test11 { public static void method1(String str)//here str is the object of string { System.out.println("String"); } public static void method1(Object obj)//here this is a common object not specified { System.out.println("Object"); } public static void main(String[] arr ) { Test11 t=new Test11(); String null1=new String(); method1(null1); method1(t); } } output is : String Object 

// null1- is a string object, if u passes this, it is called method1 (String str) only because u passes the string object // t is a general object, if u pass this, it will call method1 (Object obj) only because that u passes the objct class, so it will pass the object as a parameter

0
source

All Articles