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?
A constructor is chosen by matching the number and types of its declared parameters against the number and types of your call's arguments.
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.
All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you.
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.
Even though both constructors can accept null
, double[]
inherits from java.lang.Object
, and is therefore more specific.
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
.
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