java - 在 Java 的重载方法中使用 null

标签 java null overloading

<分区>

Possible Duplicate:
Method Overloading for NULL parameter

以下代码编译正常。

public class Main
{
    public void temp(Object o)
    {
        System.out.println("The method with the receiving parameter of type Object has been invoked.");
    }

    public void temp(String s)
    {
        System.out.println("The method with the receiving parameter of type String has been invoked.");
    }

    public void temp(int i)
    {
        System.out.println("The method with the receiving parameter of type int has been invoked.");
    }

    public static void main(String[] args)
    {
        Main main=new Main();
        main.temp(null);
    }
}

在这段代码中,要调用的方法是接受String类型参数的方法

docs说。

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.

但我不明白什么时候代码中接受原始int参数的方法之一被修改为接受包装类型Integer的参数比如,

public void temp(Integer i)
{
    System.out.println("The method with the receiving parameter of type Integer has been invoked.");
}

发出编译时错误。

reference to temp is ambiguous, both method temp(java.lang.String) in methodoverloadingpkg.Main and method temp(java.lang.Integer) in methodoverloadingpkg.Main match

在这种特殊情况下,为什么用原始数据类型重载方法是合法的,但对于其相应的包装器类型似乎并非如此?

最佳答案

如果有人问你什么是更专业的“字符串”或“对象”,你会怎么说?显然是“String”,对吧?

如果有人问你:什么是更专业的“字符串”或“整数”?没有答案,它们都是一个对象的正交特化,你如何在它们之间进行选择?然后你必须明确你想要哪一个。例如通过转换你的空引用:

question.method((String)null)

当您使用基本类型时,您不会遇到这个问题,因为“null”是一个引用类型并且不能与基本类型冲突。但是当您使用引用类型时,“null”可以引用 String 或 Integer(因为 null 可以转换为任何引用类型)。

参见 the answer in the other question我在上面的评论中发布了更多和更深入的细节,甚至是 JLS 的一些引用。

关于java - 在 Java 的重载方法中使用 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13041042/

相关文章:

ios - UIPageControl 自定义类 - 发现没有将图像更改为点

swift - 重载字典下标两次并转发调用

java - 查看 Eclipse 的源代码 - 我们如何评价算法?

php - 将静态变量设置为 null 后检查其是否为 Null

java - 在docker容器中部署.war文件: No main manifest attribute in app. war

带有空值的 MySQL where 子句

c - 使用 pow 函数时了解什么是函数重载概念

.net - 在 VBScript (COM-interop) 中确定 .Net 方法后缀号

java - 为什么 org.mindrot.JBCrypt 在这里说“盐长度错误”?

java - 具有双值的 hashMap 的 Junit 测试