5

I have this confusing code:

public class Confusing {
   private Confusing(Object o){
       System.out.println("Object");
   } 
   private Confusing(double[]dArray){
       System.out.println("double array");
   }
   public static void main(String[] args){
       new Confusing(null);
   }
}

When "compiled" and run the program displays "double array" why arrays precede Object? Is there any other constructor situation where such confusing behavior will occur?

Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
Paiku Han
  • 581
  • 2
  • 16
  • 38
  • Why the close vote? It's pretty clear what he/she is asking – But I'm Not A Wrapper Class Jun 19 '14 at 16:21
  • 1
    possible duplicate of [Which overload will get selected for null in Java?](http://stackoverflow.com/questions/1545501/which-overload-will-get-selected-for-null-in-java) and [How does Java choose which constructor to use?](http://stackoverflow.com/questions/12057333/how-does-java-choose-which-constructor-to-use) - Note the second is *exactly* the same code (homework?) – nobody Jun 19 '14 at 16:59

2 Answers2

4

A double[] is an Object too, and when choosing which constructor (or method), Java will choose the one with the most specific parameter type that still matches. Because null will match any parameter type, the most specific type matches, and that is double[] here.

It's not confusing once you know this rule, but this will occur when two or more overloaded constructors (or two or more overloaded methods) differ only in that one of the parameter types in one of them is a subclass of the corresponding parameter in another.

The JLS, Section 15.12.2.5 states how Java chooses the method/constructor to invoke when multiple overloaded methods/constructors match:

The Java programming language uses the rule that the most specific method is chosen.

and

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 error.

rgettman
  • 176,041
  • 30
  • 275
  • 357
2

Read more in Java Language Specification for choosing the Most specific method rules.

Braj
  • 46,415
  • 5
  • 60
  • 76