gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:41:04 24 4
gpt4 key购买 nike

<分区>

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com