public class OverloadingTest extends Format{
public int add(String s1){
System.out.println("With String");
return 1;
}
public int add(Object a){
System.out.println("With Object");
return 1;
}
public static void main(String[] args) {
OverloadingTest overloadingTest = new OverloadingTest();
overloadingTest.add(null);
}
}
为什么程序的输出是 With String ?
我已经尝试阅读 JLS for 6th Version,但我仍然找不到答案。
我能猜到的唯一原因是选择了继承层次结构中最接近的匹配项。
所以在这种情况下,它将采用 String,因为 Object 是它的父类(super class)。
最佳答案
此答案可在问题 Method Overloading for NULL parameter 中找到:
Java will always try to use the most specific applicable version of a method that's available (see JLS §15.12.2).
因此,String
被使用,因为它是可用的最具体的类型。如果存在多个子类型,则必须将 null
转换为适当的类型以指定要运行的函数。
关于java - 为什么这是程序的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15917641/