0

为什么Object[]调用带有类型参数的方法而不是带有类型参数的方法作为参数Object传递null

class Demo {
    void show(Object arr[]) {
        System.out.println("khawar");
    }

    public void show(Object o) {
        System.out.println("aleem");
    }

    public static void main(String[] args) {
        Demo ss=new Demo();
        ss.show(null);
    }
}
4

3 回答 3

4

Firstly, it's important to note that the null value is convertible to both Object and Object[], so both methods are applicable. Then it's just a matter of overload resolution. That's described in section 15.12 of the JLS, and section 15.12.2.5 in particular talks about finding "the most specific method", which includes:

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.

That's the case here: any invocation of show(Object[]) can be passed to show(Object) without a compile-time type error, therefore show(Object[]) is more specific than show(Object), so overload resolution picks show(Object[]) to invoke.

To invoke show(Object) you just have to cast the null to Object, to stop the show(Object[]) method from being applicable:

ss.show((Object) null);
于 2013-10-29T07:22:15.957 回答
2

您必须通过 JLS 找到确切的解释,但基本上原因是,选择了最具体的方法签名,并且“null”作为子类比超类更具体的匹配。

// Where Subclass extends Middleclass extends Superclass
public void method(Superclass c) {}
public void method(Middleclass m) {}
public void method(Subclass s) {}

在上述情况下,调用method(null)将调用method(Subclass s).

于 2013-10-29T07:20:01.070 回答
0

当匹配多个候选人时,将选择最具体的签名。Object[] 一个Object,因此更具体的地方Object是更通用的。

例如,如果您添加,show(Integer[])那么这将是最具体的候选人,并且将被选中show(Object[])。如果您同时添加了两者show(Integer[])show(String[])那么您将得到一个编译时错误,指定show(Object)是模棱两可的,因为这两种新添加的方法都是对您尝试进行的调用具有相同特异性的候选方法。

如果你想强制调用show(Object),那么你可以写:show((Object)null);

于 2013-10-29T07:32:07.083 回答