简体   繁体   English

在Java中混淆​​方法重载

[英]Confusing method overloading in Java

Following is the code relevant to constructor overloading in Java. 以下是与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). 在上面的代码中,构造函数正在被重载,其中一个具有Object类型的形式参数,另一个具有类型为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. 其中一个构造函数由上面的语句调用,该语句使用null值作为它的实际参数,程序在控制台上显示输出double数组 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: 它在编译时被解析为double[] ,因为它是解决的最具体的成员:

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编程语言使用选择最具体方法的规则。

Java will call the most-specific constructor possible. Java将调用最具体的构造函数。

See Class Instance Creation Expressions ( JLS 15.9 ) and Method Invocation Expressions ( JLS 15.12 ) 请参见类实例创建表达式JLS 15.9 )和方法调用表达式JLS 15.12

Object is the superclass of all classes. Object是所有类的超类。 Hence the most specific type that matches the arguments will be called and by this it is resolved at compile time. 因此,将调用与参数匹配的最具体类型,并且在编译时它将被解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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