Reputation: 30513
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 what criteria Java compiler decided to go with String method? Can somebody please point me the reason for this?
Upvotes: 3
Views: 329
Reputation: 718816
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.
Upvotes: 2
Reputation: 17014
Addressed here:
Overloaded method selection based on the parameter's real type
Upvotes: 0
Reputation: 81684
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
Upvotes: 12