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

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

问题描述

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

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

这个程序的输出是字符串版本".但是我无法理解为什么将 null 传递给重载方法选择了字符串版本.null 是一个指向空的字符串变量吗?

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

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

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

推荐答案

null 是一个指向空的字符串变量吗?

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 编译器根据 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.

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

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天全站免登陆