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");
}
}
结果是字符串。解释为什么?
最佳答案
因为选择了最具体的方法,所以最具体的是String
(与Object
相比)。顺便说一句,这是在 JLS 中......我很快就会把它挖出来。
根据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.
关于java - 将参数传递给重载函数的一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52223537/