2

Why does the compiler match the String overload, and not the Object overload?

public static void main(String[] args) {
    method(null);
}

public static void method(Object o) {
    System.out.println("Object impl");
}

public static void method(String s) {
    System.out.println("String impl");
}
StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • 4
    I think the JVM will always call the more specific matching signature when there are multiple matches. `String` is more specific than `Object`, so it gets called. – Tim Biegeleisen May 17 '18 at 05:42
  • OK. Try this: Object o = null; method(o); :D – nick May 17 '18 at 06:06
  • 2
    Tim is right, the [Java language specification](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2.5) requires that the most specific method is called and `String` is more specific than `Object`. – dave May 17 '18 at 06:12

2 Answers2

1

It is executing the string because it will find the near match of the null but if you try int and object as method parameter. then it will choose the object method to print.

ayushs27
  • 97
  • 1
  • 8
1

Java Compiler chooses the most specific method.String is a more specific type compared to the Object.