gpt4 book ai didi

java - 在具有重载构造函数的类中传递 null 时首先调用哪个构造函数?

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

下面是具有 3 个重载构造函数的 java 类:

public class Test {

public Test(Object i){
System.out.println("Object invoked");
}

public Test(String i){
System.out.println("String invoked");
}

public Test(int k){
System.out.println("Integer invoked");
}

public static void main(String[] args) throws Exception {

Test t = new Test(null);
}
}

如果在创建类的新实例时传递了空值,将调用哪个构造函数?这是什么原因?

最佳答案

Java 总是选择适用于您传递的参数的最具体 方法(或构造函数)。在本例中,这是 String 构造函数——StringObject 的子类。

想想如果你有会发生什么

new Test("some string")

ObjectString 构造函数都适用于此。毕竟,参数既是 Object 又是 String但是,很明显 String 构造函数将被调用,因为它比 Object 构造函数更具体并且在给定参数的情况下仍然适用。

null 也不异常(exception);这两个构造函数仍然适用,出于同样的原因,仍然选择 String 构造函数而不是 Object 构造函数。

现在,如果存在两个同样“特定”的构造函数(例如,如果您有一个 Integer 构造函数),那么当您调用 Test(null).

这在 JLS §15.12.2 中有更详细的概述。 :

The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments.

There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run time to perform the method dispatch.

JLS §15.12.2.5 中概述了确定哪种方法最具体的明确过程。 .

关于java - 在具有重载构造函数的类中传递 null 时首先调用哪个构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18803056/

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