Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Overloading concept [duplicate]

When I run this code it prints String. My question is why there is no compile time error? Default value of Object and as well as String is null. Then why not compiler says 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);    
   }
}
like image 560
Deepak Avatar asked Mar 06 '13 12:03

Deepak


2 Answers

From this answer:

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

This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable There may be more than one such method, in which case the most specific one is chosen.

like image 145
Waleed Khan Avatar answered Oct 23 '22 15:10

Waleed Khan


The compiler will look at all the possible overloads of the method that could match the parameters you pass. If one of them is more specific than all the others then it will be chosen, it's only 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 is more specific than Object there's no ambiguity, and the String option will be chosen. If there were a third overload such as method1(Integer) then there is no longer a single most specific choice for the call method1(null), and the compiler would generate an error.

like image 43
Ian Roberts Avatar answered Oct 23 '22 15:10

Ian Roberts