Following is the code relevant to constructor overloading in Java. Let's have a look at it.
package temp;
final public class Main
{
private Main(Object o)
{
System.out.println("Object");
}
private Main(double[] da)
{
System.out.println("double array");
}
public static void main(String[] args)throws Exception
{
Main main = new Main(null);
}
}
In the above code, constructors are being overloaded in which one has a formal parameter of type Object and the other has the formal parameter of type double (array).
Main main = new Main(null);
One of the constructors is being invoked by the above statement which is using a null value as it's actual argument and the program is displaying the output double array on the console. How does the compiler resolve a specific constructor (or a method, if such is a case) dynamically at run time in such a situation?
It's resolved at compile time to double[], because it's the most specific member to resolve to:
If more than one member method is both accessible and applicable to a method invocation, [...] The Java programming language uses the rule that the most specific method is chosen.
Java will call the most-specific constructor possible.
See Class Instance Creation Expressions (JLS 15.9) and Method Invocation Expressions (JLS 15.12)
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