Java Reference
In-Depth Information
< Day Day Up >
Puzzle 46: The Case of the Confusing Constructor
This puzzle presents you with two Confusing constructors. The main method invokes a constructor,
but which one? The program's output depends on the answer. What does the program print, or is it
even legal?
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);
}
}
Solution 46: Case of the Confusing Constructor
The parameter passed to the constructor is the null object reference, so at first glance, it seems that
the program should invoke the Object overloading and print Object . On the other hand, arrays are
reference types too, so null could just as well apply to the double[] overloading. You might
therefore conclude that the call is ambiguous, which suggests that the program shouldn't compile. If
you tried running the program, you found that neither of these intuitions is correct: The program
prints double array . This behavior may seem perverse, but there is a good reason for it.
Java's overload resolution process operates in two phases. The first phase selects all the methods or
constructors that are accessible and applicable. The second phase selects the most specific of the
 
 
Search WWH ::




Custom Search