java - 备用构造函数调用

标签 java constructor

我一直在读 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/

相关文章:

c++ - 可重用的构造函数 C++

Windows 系统上的 Java 应用程序作为 USB 外设运行

Java网络应用程序: where/how to automatically set each picture's width/height

java - 如何优雅地处理 Kafka 中断?

java - Java 构造函数的默认访问修饰符

c++ - 将相同的参数转发给 C++ 中的可变元组构造函数

java - 如何使用Java Beans和jsp标签在Postgres数据库中插入数据?

java - libgdx- 像素图 : can I somehow change the width of the line?

java - 在 java 中需要默认构造函数吗?

c++ - 如何在已分配的内存上调用构造函数?