gpt4 book ai didi

java - 令人困惑的Java方法重载

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:55:11 26 4
gpt4 key购买 nike

以下是Java中与构造函数重载相关的代码。我们来看看。

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);
}
}

在上面的代码中,构造函数被重载,其中一个具有 Object 类型的形参,另一个具有 double(数组)类型的形参。


Main main = new Main(null);

上面的语句调用了一个构造函数,该语句使用 null 值作为实际参数,程序在控制台上显示输出 double array .在这种情况下,编译器如何在运行时动态解析特定的构造函数(或方法,如果是这种情况)?

最佳答案

它在编译时解析为double[],因为它是most specific成员决定:

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方法重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8131203/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com