0
package java_coding;

public class String_Null {
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String_Null string_Null = new String_Null();
    string_Null.method(null);
}

public void method(String string) {
    System.out.println("String");
}

public void method( Object object) {

    System.out.println("Object");
}


}

The result is String. Explain why?

codeLover
  • 2,571
  • 1
  • 11
  • 27
ZhanqiRen
  • 1
  • 2

1 Answers1

2

Because the most specific method is chosen, the most specific is String (compared to Object). This is in the JLS btw... I'll dig this up shortly.

According to the JLS

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run- time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Eugene
  • 117,005
  • 15
  • 201
  • 306