0

我知道原始数据类型的自动类型提升概念。但是在引用数据类型的情况下,我有下面的代码可以完美运行。

public class Test4 {

void set(Object o) {
    System.out.println("Inside Object");
}

void set(double[] a) {
    System.out.println("Array");
}
public static void main(String[] args) {
    new Test4().set(null);

}
}

这给出了输出数组。

但是如果代替 Object o,如果我们有任何其他类,那么这将显示编译时错误该方法对于类型 Test4 不明确

下面的代码给出了编译时错误

public class Test4 {

/*void set(Object o) {
    System.out.println("Inside Object");
}*/

void set(String s) {
    System.out.println("String");
}
void set(double[] a) {
    System.out.println("Array");
}
public static void main(String[] args) {
    new Test4().set(null);

}

}

据我所知,每个引用数据类型(类、接口和数组)的默认值为 null。

那么为什么上面的代码在 Object o 的情况下有效。

提前致谢

4

3 回答 3

7

Compiler always chooses the method with more specific parameter type, that can match the passed argument, in case that argument can be used for both parameters.

Since, null is valid value for String, Object, double[], so the compiler has to decide which method to invoke.

  • In case of Object and double[], since double[] is more specific than Object(an array is nothing but an Object). So compiler will choose the more specific type here - double[].
  • In case of String and double[], compiler can't decide which one is more specific type, as there isn't any relation between array and String type (They don't fall in same inheritance hierarchy). So it takes the call as ambiguous.

You can go through JLS §15.12.2.5 - Choosing the Most Specific Method

于 2013-07-29T18:33:33.453 回答
0

因为double[]更具体。

double[]Object。所以当你调用set(some-double-array)这个版本时被调用。注意,null没问题double[]

但在第二种情况下,没有更具体的方法。

于 2013-07-29T18:31:41.787 回答
-3

Because, Object is not a datatype, whenever user enters some data, it decides its datatype. For example, Object obj = null; //Wrong syntax

Object obj = 4.0; //here the obj is double, as the passed value is 4.0

Object obj = "raj"; //here obj is string.

Object is same as var in javascript.

于 2013-07-29T18:37:14.943 回答