6

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);    
   }
}
Harry Joy
  • 58,650
  • 30
  • 162
  • 207
Deepak
  • 63
  • 3

4 Answers4

3

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.

Community
  • 1
  • 1
Waleed Khan
  • 11,426
  • 6
  • 39
  • 70
2

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.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
0

Well in one sentence

In case of Overloaded methods compiler chooses the method with most specific type, as String is the most specific type of Object compiler will invoke the method which takes string as an argument

PermGenError
  • 45,977
  • 8
  • 87
  • 106
0
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 pass this it will call method1(String str) only because u pass string object //t-is general object if u pass this it will call method1(Object obj)only because u pass class objct so it will pass object as parameter

Francis Stalin
  • 439
  • 1
  • 4
  • 14