Tin*_*iny 6 java null overloading
可能重复:
NULL参数的方法重载
以下代码编译并正常运行.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在此代码中,要调用的方法是接受类型参数的方法 String
该文档说.
如果多个成员方法都可访问并适用于方法调用,则必须选择一个为运行时方法调度提供描述符.Java编程语言使用选择最具体方法的规则.
但我不明白当代码中接受原语参数的方法之一int被修改为接受包装类型的参数时,Integer如:
public void temp(Integer i)
{
System.out.println("The method with the receiving parameter of type Integer has been invoked.");
}
Run Code Online (Sandbox Code Playgroud)
发出编译时错误.
对temp的引用是不明确的,methodoverloadingpkg.Main中的方法temp(java.lang.String)和methodoverloadingpkg.Main中的方法temp(java.lang.Integer)匹配
在这个特定的场景中,为什么使用原始数据类型重载方法是合法的,但是它的相应包装类型似乎不是这种情况呢?
Edw*_*rzo 17
如果你被问到什么是更专业的"字符串"或"对象",你会说什么?显然是"字符串",对吧?
如果有人问你:什么是更专业的"字符串"或"整数"?没有答案,它们都是对象的正交特化,你如何在它们之间进行选择?那么你必须明确你想要哪一个.例如,通过转换null引用:
question.method((String)null)
Run Code Online (Sandbox Code Playgroud)
当您使用原始类型时,您没有这个问题,因为"null"是一个引用类型,不能与基本类型冲突.但是当你使用引用类型时,"null"可以引用String或Integer(因为null可以转换为任何引用类型).
请参阅我在上述评论中发布的另一个问题中的答案,以获取更多更深入的详细信息,甚至是JLS的一些引用.