public class test {
test(double[] a)
{
System.out.println("in double");
}
test(Object a)
{
System.out.println("in object");
}
public static void main(String args[])
{
new test(null);
}
}
In the above code, I pass null
as the constructor argument. As null
can be anything, the above code compiles fine. When I run the code I expected it to print in object but it prints in double
What is the reason behind this?
NOTE the linked question may not be duplicate because this question is related with primitive datatype vs Object
Both constructors are applicable, because null
is convertible to both Object
and double[]
- so the compiler needs to use overload resolution to determine which constructor to call.
JLS 15.9.3 uses JLS 15.12.2 to determine the "most specific" constructor signature to use, based on which constructor has the most specific parameter types, according to JLS 15.12.2.5. The exact details are slightly obscure (IMO) but in this case the basic rule of thumb of "if you can convert from T1 to T2, but not T2 to T1, then T1 is more specific" is good enough.
double[]
is a more specific type than Object
, because there's an implicit conversion from double[]
to Object
, but not vice versa.
See more on this question at Stackoverflow