gpt4 book ai didi

java - 为什么这是程序的输出?

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

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/

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