简体   繁体   中英

Confusing method overloading in 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?

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 )

Object is the superclass of all classes. Hence the most specific type that matches the arguments will be called and by this it is resolved at compile time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM