How does Java decide between methods with the same name with different parameter types?
public class Main {
public void testMethod(Object o){
System.out.println("Object Method called");
}
public void testMethod(String s){
System.out.println("String Method called");
}
public static void main(String[] args) {
new Main().testMethod(null);
}
}
This program magically calls String method? On w开发者_如何转开发hat criteria Java compiler decided to go with String method? Can somebody please point me the reason for this?
The rule is that the compiler chooses the "most specific" overload out of all matches. Since String is a subclass of Object, that makes the String version "more specific", and hence it is chosen
The operative part of the Java Language Specification is JLS 15.12.2.5:
"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 type error."
The JLS then proceeds to give a detailed technical specification of how to determine the most specific method.
Addressed here:
Overloaded method selection based on the parameter's real type
精彩评论