Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Java choose which constructor to use?

Tags:

java

I am not able to understand the output of the following program.

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);
    }
}

The correct output is "double array". WHy was this constructor chosen as more specific than the other when both can accept null?

like image 904
user1614482 Avatar asked Aug 21 '12 14:08

user1614482


People also ask

How does Java determine which constructor to use?

A constructor is chosen by matching the number and types of its declared parameters against the number and types of your call's arguments.

Will Java provide default constructor by own how?

Java compiler automatically creates a default constructor (Constructor with no arguments) in case no constructor is present in the java class. Following are the motive behind a default constructor. Initialize all the instance variables of the class object.

Does every class have a default constructor Java?

All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you.

How are constructors called in Java?

The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created.


2 Answers

Even though both constructors can accept null, double[] inherits from java.lang.Object, and is therefore more specific.

like image 83
Sergey Kalinichenko Avatar answered Oct 16 '22 18:10

Sergey Kalinichenko


The challenge of compiling dynamically typed languages is how to implement a runtime system that can choose the most appropriate implementation of a method or function — after the program has been compiled. Treating all variables as objects of Object type would not work efficiently.

Hence, choosing the specific one over Object.

like image 44
Kazekage Gaara Avatar answered Oct 16 '22 18:10

Kazekage Gaara