当参数是文字空值时,如何选择重载方法? [英] How is an overloaded method chosen when a parameter is the literal null value?

查看:181
本文介绍了当参数是文字空值时,如何选择重载方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I came across this question in a quiz,

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是一个指向什么都没有的String变量?

The output of this program is "String Version". But I was not able to understand why passing a null to an overloaded method chose the string version. Is null a String variable pointing to nothing ?

但是当代码更改为时,

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类型是不明确的

it gives a compile error saying "The method method(StringBuffer) is ambiguous for the type MoneyCalc"

推荐答案


null是一个指向什么都没有的String变量?

Is null a String variable pointing to nothing ?

空引用可以转换为任何类类型的表达式。所以在 String 的情况下,这很好:

A null reference can be converted to an expression of any class type. So in the case of String, this is fine:

String x = null;

选择 String 重载是因为Java编译器根据最具体的重载15.12.2.5rel =noreferrer> JLS的第15.12.2.5节。特别是:

The String overload here is chosen because the Java compiler picks the most specific overload, as per section 15.12.2.5 of the JLS. In particular:


非正式的直觉是,如果第一种方法处理的任何调用都可以传递给一个方法,那么一种方法比另一种方法更具体没有编译时类型错误的另一个。

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.

在你的第二种情况下,两种方法仍然适用,但都不是字符串也不是 StringBuffer 比其他方法更具体,因此这两种方法都不比其他方法更具体,因此编译错误。

In your second case, both methods are still applicable, but neither String nor StringBuffer is more specific than the other, therefore neither method is more specific than the other, hence the compiler error.

这篇关于当参数是文字空值时,如何选择重载方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆