gpt4 book ai didi

java - 当参数为空值时,如何选择重载方法?

转载 作者:太空宇宙 更新时间:2023-11-04 14:30:38 24 4
gpt4 key购买 nike

我在测验中遇到了这个问题,

public class MoneyCalc {

public void method(Object o) {
System.out.println("Object Verion");
}

public void method(String s) {
System.out.println("String Version");
}

public static void main(String args[]) {
MoneyCalc question = new MoneyCalc();
question.method(null);
}
}

该程序的输出是“String Version”。但我无法理解为什么将 null 传递给重载方法会选择字符串版本。 null 是一个不指向任何内容的字符串变量吗?

但是当代码更改为时,

public class MoneyCalc {

public void method(StringBuffer sb) {
System.out.println("StringBuffer Verion");
}

public void method(String s) {
System.out.println("String Version");
}

public static void main(String args[]) {
MoneyCalc question = new MoneyCalc();
question.method(null);
}
}

它给出一个编译错误,指出“方法 method(StringBuffer) 对于 MoneyCalc 类型来说不明确”

最佳答案

Is null a String variable pointing to nothing ?

空引用可以转换为任何类类型的表达式。因此,对于 String 来说,这样就可以了:

String x = null;

此处选择String 重载是因为Java 编译器选择最具体 重载,如section 15.12.2.5 of the JLS 所示。 。特别是:

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

在第二种情况下,这两种方法仍然适用,但是 StringStringBuffer 都不比另一个更具体,因此这两种方法都不比另一个更具体,因此编译器错误。

关于java - 当参数为空值时,如何选择重载方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26205808/

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