0

I know the automatic type promotion concept in case of primitive data type.But in case of reference data type I have below code which works perfectly.

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

}
}

which gives output Array.

But if in place of Object o,if we have any other class then this will show compile time error The method is ambiguous for the type Test4

Below code gives compile time error

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

}

}

As i know default value of every reference data type (Class,Interface and Array) is null.

So why above code is working in case of Object o.

Thanks in advance

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
Arun
  • 1,038
  • 2
  • 12
  • 25

3 Answers3

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

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

Because double[] is more specific.

double[] is Object. So when you call set(some-double-array) this version is called. Note, that null is fine double[]

But in the second case there's no more specific method.

RiaD
  • 46,822
  • 11
  • 79
  • 123
-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.

  • 2
    This is completely wrong. Object is *not* the same as JavaScript var. This is perfectly legal: `Object o = new Object();` and `Object obj = null;`. It even compiles. Maybe you're thinking of a language other than Java? – Roddy of the Frozen Peas Jul 29 '13 at 18:48