我在我的程序中遇到了一个问题,我用下面的一小段代码清楚地说明了这一点。谁能解释为什么会这样?
class ObjectnullTest {
public void printToOut(String string) {
System.out.println("I am null string");
}
public void printToOut(Object object)
System.out.println("I am null object");
}
class Test {
public static void main(String args[]) {
ObjectnullTest a = new ObjectnullTest();
a.printToOut(null);
}
}
这总是打印 I am null string
。
我想知道原因,以便修改代码。
最佳答案
因为在方法重载的情况下
The most specific method is choosen at compile time.
因为“java.lang.String”是比“java.lang.Object”更特定的类型。在您的情况下,选择了将“String”作为参数的方法。
它在 JLS 中有明确记录:
The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments.
There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run-time to perform the method dispatch.
关于java - 将 null 传递给首选 String 而不是 Object 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15046763/