Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing method overloading in Java

Tags:

java

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?

like image 549
Lion Avatar asked Feb 06 '26 07:02

Lion


2 Answers

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.

like image 184
Jordão Avatar answered Feb 07 '26 20:02

Jordão


Java will call the most-specific constructor possible.

See Class Instance Creation Expressions (JLS 15.9) and Method Invocation Expressions (JLS 15.12)

like image 30
Dave Newton Avatar answered Feb 07 '26 20:02

Dave Newton