java - 将 null 传递给不明确的重载方法

标签 java overloading

以下方法将调用哪个重载方法?为什么

我执行了这段代码,它使用 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 实现都是 的子类对象

来自JLS Sec 15.12.2.5 :

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) 重载,它将无法编译,因为 ListString 是“同样”特定的。 (或任何其他类:它不必是 String)。

关于java - 将 null 传递给不明确的重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39189080/

相关文章:

java - R.layout.main 无法解析

java - SOAP - 没有命名空间的前缀

java - MaxTenuringThreshold - 它到底是如何工作的?

C++ 函数重载、表达式模板和命名空间

c++ - 从文件读取时如何创建对象 vector ? [C++]

java - Kotlin 模块源未打包在 aar 中

java - Docker 容器与 2 个应用程序交互

c++ - 运算符 >> 重载结构?

c# - 可选参数: reversed precedence if override of overload exists

c++ - 使用可转换类型调用重载函数时模板构造函数歧义