空参数的方法重载 [英] Method Overloading for null argument

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

问题描述

我添加了三个带参数的方法:

I have added three methods with parameters:

public static  void doSomething(Object obj) {
    System.out.println("Object called");
}

public static  void doSomething(char[] obj) {
    System.out.println("Array called");
}

public static  void doSomething(Integer obj) {
    System.out.println("Integer called");
}

当我调用 doSomething(null) 时,编译器将错误作为模棱两可的方法抛出.那么问题是因为 Integerchar[] 方法还是 IntegerObject 方法?

When I am calling doSomething(null) , then compiler throws error as ambiguous methods. So is the issue because Integer and char[] methods or Integer and Object methods?

推荐答案

Java 将始终尝试使用可用方法的最具体的适用版本(请参阅 JLS §15.12.2).

Java will always try to use the most specific applicable version of a method that's available (see JLS §15.12.2).

Objectchar[]Integer 都可以将 null 作为有效值.所以这三个版本都适用,所以Java必须找到最具体的一个.

Object, char[] and Integer can all take null as a valid value. Therefore all 3 version are applicable, so Java will have to find the most specific one.

由于Objectchar[] 的超类型,数组版本比Object 版本更具体.因此,如果仅存在这两种方法,则将选择 char[] 版本.

Since Object is the super-type of char[], the array version is more specific than the Object-version. So if only those two methods exist, the char[] version will be chosen.

char[]Integer 版本都可用时,那么两者都比Object更具体code> 但没有一个比另一个更具体,因此 Java 无法决定调用哪个.在这种情况下,您必须通过将参数强制转换为适当的类型来明确提及要调用的那个.

When both the char[] and Integer versions are available, then both of them are more specific than Object but none is more specific than the other, so Java can't decide which one to call. In this case you'll have to explicitly mention which one you want to call by casting the argument to the appropriate type.

请注意,在实践中,此问题的发生比人们想象的要少得多.这样做的原因是,它仅在您使用 null 或相当不特定类型的变量(例如 Object)显式调用方法时才会发生.

Note that in practice this problem occurs far more seldom than one might think. The reason for this is that it only happens when you're explicitly calling a method with null or with a variable of a rather un-specific type (such as Object).

相反,以下调用将完全明确:

On the contrary, the following invocation would be perfectly unambiguous:

char[] x = null;
doSomething(x);

尽管您仍在传递值 null,但 Java 确切地知道要调用哪个方法,因为它会考虑变量的类型.

Although you're still passing the value null, Java knows exactly which method to call, since it will take the type of the variable into account.

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

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