2

I tried the following code, but don't understand the output:

Class A{
  public void print(Object o){
     System.out.println("Object");
  }
  public void print(String o){
     System.out.println("String");
  }  
  public static void main(String arr[]){
     A obj = new A();
     obj.print(null);
  }
}

Output: String

Why??

Thanks for your attention!

Eran
  • 387,369
  • 54
  • 702
  • 768
Deepu--Java
  • 3,742
  • 3
  • 19
  • 30

3 Answers3

2

The method with the more specific argument type is chosen. String is more specific than Object.

Note that if you had another print method with, say, an Integer parameter, you would get a compilation error, since in that case the compiler would have no rule to decide whether to call print(String) or print(Integer). The reason it works when you have print(String) and print(Object) is that String is a sub-class of Object, and therefore print(String) is preferred.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

If there's method overloading, the compiler search for the method from the most specific type to least specific type

From JLS specification

15.12.2.5. Choosing the Most Specific Method

So String is a more specific type compared to the Object.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
1

The least generic method among the matching methods will be selected by the compiler. i.e, the compiler will first find out that both String and Object can be null. Then it selects the one which is at a lower level in the class hierarchy. (Object is at a higher level than String)

TheLostMind
  • 35,966
  • 12
  • 68
  • 104