6

I found this Java code from this site. I don't understand how it compiles without 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
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Sitansu
  • 3,225
  • 8
  • 34
  • 61

1 Answers1

6

null can be passed to both JavaTest(String arg) and JavaTest(Object obj), so the compiler chooses the method with the more specific argument types. Since String is more specific than Object (String being a sub-class of Object), JavaTest(String arg) is chosen.

If instead of JavaTest(Object obj) you had JavaTest(Integer obj), the compilation would have failed, since Integer is not more specific than String and String is not more specific thanInteger`, so the compiler wouldn't be able to make a choice.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    But `Integer` also allow `Null` even then it will fail? – Subodh Joshi Aug 11 '15 at 06:51
  • 1
    @SubodhJoshi Yes, integer allows null, so the compiler wouldn't be able to choose between `JavaTest(String arg)` and `JavaTest(Integer obj)`. – Eran Aug 11 '15 at 06:53
  • Sorry But i don't able to understand what the issue to choose from `JavaTest(String arg)` and `JavaTest(Integer obj)`..When Compiler can choose between `JavaTest(String arg)` and `JavaTest(Object obj)` We know `Object` can be `Null`,`String` can be `Null` and `Integer` can be `Null` ? – Subodh Joshi Aug 11 '15 at 06:57
  • 1
    @SubodhJoshi If two methods have the same names, the same number of arguments and both can accept the parameters you are passing (`null` in this example), the compiler must somehow choose between them. If one method has an argument more specific than the other (as String is more specific than Object), the method with the more specific argument is chosen. Otherwise, the code doesn't pass compilation, since the compiler can't make a choice. – Eran Aug 11 '15 at 07:02
  • 1
    @SubodhJoshi compiler tries to find best option(Identifying its type) to pass the null as String is more clear type than object because String can have only String value while Object can have String ,Integer etc value So the apropriate type would be String in case of String and Object but incase of String and Integer they both have same priority so the compiler would be confused – singhakash Aug 11 '15 at 07:04