Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why constructors with array as parameter precede constructors with Object in parameter [java]? [duplicate]

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?

like image 545
Paiku Han Avatar asked Jun 19 '14 16:06

Paiku Han


People also ask

Can we pass array as argument in constructor?

To pass an array to a constructor we need to pass in the array variable to the constructor while creating an object.

Can we create an array of objects for a class having user defined constructor?

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.

Which are reasons to overload a constructor in Java?

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.

How do you create an array of objects from a constructor in Java?

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.


1 Answers

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.

like image 195
rgettman Avatar answered Nov 15 '22 00:11

rgettman