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

标签 java overloading

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

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);
   }
}

这个程序的输出是“字符串版本”。但我无法理解为什么将 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);
   }
}

它给出了一个编译错误,说“方法方法(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/13033037/

相关文章:

java - 美国 map 的四色定理Java实现

c++ - 这是重载提供与非静态成员函数相同接口(interface)的静态成员函数的优雅方法吗?

c++ - 在这种情况下,为什么 g++ 和 clang 会破坏 namespace 抽象?

java - 设置 NativeSelect 的自定义值

java - 使用 jframe 时找不到符号错误

java - 如何从 Java 获取空闲内存信息

java - 发送电子邮件 phpmailer 和 javax.mail

c++ - 模板参数的隐式转换规则

java - 在抽象类中重载抽象方法

Python函数重载