gpt4 book ai didi

java - 备用构造函数调用

转载 作者:行者123 更新时间:2023-12-01 21:57:58 25 4
gpt4 key购买 nike

我一直在读 article 关于 Java 中的构造函数,并遇到以下文本:

Execution of instance variable initializers and instance initializers is performed regardless of whether the superclass constructor invocation actually appears as an explicit constructor invocation statement or is provided automatically. (An alternate constructor invocation does not perform this additional implicit execution.)

我对括号里的句子有点不清楚。这是否意味着如果我们不显式指定要调用的备用构造函数,它就不会被隐式调用为 this(),对吗?

最佳答案

是的。这就是说,您总是会调用 super() 构造函数作为构造函数中的第一个语句(除非您使用 this(),但这样就会有super() 调用作为第一个语句 - 或备用调用,最终将调用 super())。

考虑一下假设类(如 Main)的空构造函数中会发生什么,该类具有一个 String value 字段和三个构造函数(如

)
private String value;

public Main() {
this(10); // alternate constructor, super() isn't invoked yet.
}

public Main(int val) {
this(String.valueOf(val)); // alternate constructor, no super() yet
}

public Main(String str) {
// super(); // <-- will now implicitly or explicitly super()
this.value = str;
}

关于java - 备用构造函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27075290/

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