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?
To pass an array to a constructor we need to pass in the array variable to the constructor while creating an object.
One way to initialize the array of objects is by using the constructors. When you create actual objects, you can assign initial values to each of the objects by passing values to the constructor. You can also have a separate member method in a class that will assign data to the objects.
The constructor overloading enables the accomplishment of static polymorphism. The class instances can be initialized in several ways with the use of constructor overloading. It facilitates the process of defining multiple constructors in a class with unique signatures.
Creating an Array Of Objects In Java – An Array of Objects is created using the Object class, and we know Object class is the root class of all Classes. We use the Class_Name followed by a square bracket [] then object reference name to create an Array of Objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With