我在一次测验中遇到了这个问题,
public class MoneyCalc {
public void method(Object o) {
System.out.println("Object Verion");
}
public void method(String s) {
System.out.println("String Version");
}
public static void main(String args[]) {
MoneyCalc question = new MoneyCalc();
question.method(null);
}
}
这个程序的输出是“字符串版本”。但我无法理解为什么将 null 传递给重载方法会选择字符串版本。 null 是一个指向空的字符串变量吗?
但是当代码改为,
public class MoneyCalc {
public void method(StringBuffer sb) {
System.out.println("StringBuffer Verion");
}
public void method(String s) {
System.out.println("String Version");
}
public static void main(String args[]) {
MoneyCalc question = new MoneyCalc();
question.method(null);
}
}
它给出了一个编译错误,说“方法方法(StringBuffer)对于MoneyCalc类型不明确”
最佳答案
Is null a String variable pointing to nothing ?
空引用可以转换为任何类类型的表达式。所以在 String
的情况下,这很好:
String x = null;
这里选择String
重载是因为Java 编译器会根据section 15.12.2.5 of the JLS 选择最具体的 重载。 .特别是:
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.
在您的第二种情况下,这两种方法仍然适用,但 String
和 StringBuffer
都没有比另一种更具体,因此没有一种方法比另一种更具体,因此编译器错误。
关于java - 当参数是文字空值时,如何选择重载方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13033037/