以下方法将调用哪个重载方法?为什么?
我执行了这段代码,它使用 List 调用了重载方法,但是为什么会发生这种情况?
public class AmbigiousOverload {
public static void add(Object o) {
System.out.println("Overloaded method with Object.");
}
public static void add(List l) {
System.out.println("Overloaded method with List.");
}
public static void main(String[] args) {
add(null);
}
}
输出:Overloaded method with List.
最佳答案
调用 List
重载是因为 List
重载是最具体的匹配重载,因为所有 List
实现都是 的子类对象
。
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.
由于您可以传递给 add(List)
的任何参数也可以传递给 add(Object)
,因此 add(List)
是更具体。因此,鉴于 null
可以传递给两者,因此选择更具体的方法。
请注意,如果您有 add(String)
重载,它将无法编译,因为 List
和 String
是“同样”特定的。 (或任何其他类:它不必是 String
)。
关于java - 将 null 传递给不明确的重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39189080/