为什么要在所有构造函数中显式初始化一个空白的最终变量?
Why should a blank final variable be explicitly initialised in all constructors?
我刚开始阅读Java。让我感到困惑的一件事是,在 class 的所有构造函数中都应该初始化一个空白的最终变量。如果我有一个带有 3 个构造函数的 class,并且我在一个构造函数中初始化了一个空白的 final 变量,为什么我还需要在其他两个构造函数中初始化相同的空白 final 变量?
final 变量必须在创建 class 实例时初始化(即在构造函数执行完成后)。
如果您使用不初始化空白 final 变量的构造函数之一创建 class 的实例,则在构造函数执行完成后将不会初始化 final 变量。
因此所有构造函数都必须初始化空白最终变量。
这是假设 none 个构造函数使用 this()
调用不同的构造函数。
J.L.S Chapter 16. Definite Assignment
Each local variable (§14.4) and every blank final field (§4.12.4, §8.3.1.2) must have a definitely assigned value when any access of its value occurs.
如果您使用不初始化空白 final 字段的构造函数创建 class 的实例,您可能会在分配该字段之前访问该字段。因此编译器不允许。
这是因为在创建 class 的实例时只执行一个构造函数。
我更喜欢有一个构造函数作为最常用的构造函数,并从其他构造函数中调用它。在一个构造函数中,您可以通过 this(...)
调用相同 class 的另一个构造函数。示例:
class MyClass {
private final int a;
private final String b;
private double c;
/**
* Most common constructor.
*/
public MyClass(int a, String b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public MyClass(int a, String b) {
this(a, b, 0.0);
}
public MyClass(double c) {
this(0, null, c);
}
// other constructors as needed
}
这样一来,您就集中了在一个构造函数中初始化实例的责任。其他构造函数依赖于那个。
我刚开始阅读Java。让我感到困惑的一件事是,在 class 的所有构造函数中都应该初始化一个空白的最终变量。如果我有一个带有 3 个构造函数的 class,并且我在一个构造函数中初始化了一个空白的 final 变量,为什么我还需要在其他两个构造函数中初始化相同的空白 final 变量?
final 变量必须在创建 class 实例时初始化(即在构造函数执行完成后)。
如果您使用不初始化空白 final 变量的构造函数之一创建 class 的实例,则在构造函数执行完成后将不会初始化 final 变量。
因此所有构造函数都必须初始化空白最终变量。
这是假设 none 个构造函数使用 this()
调用不同的构造函数。
J.L.S Chapter 16. Definite Assignment
Each local variable (§14.4) and every blank final field (§4.12.4, §8.3.1.2) must have a definitely assigned value when any access of its value occurs.
如果您使用不初始化空白 final 字段的构造函数创建 class 的实例,您可能会在分配该字段之前访问该字段。因此编译器不允许。
这是因为在创建 class 的实例时只执行一个构造函数。
我更喜欢有一个构造函数作为最常用的构造函数,并从其他构造函数中调用它。在一个构造函数中,您可以通过 this(...)
调用相同 class 的另一个构造函数。示例:
class MyClass {
private final int a;
private final String b;
private double c;
/**
* Most common constructor.
*/
public MyClass(int a, String b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public MyClass(int a, String b) {
this(a, b, 0.0);
}
public MyClass(double c) {
this(0, null, c);
}
// other constructors as needed
}
这样一来,您就集中了在一个构造函数中初始化实例的责任。其他构造函数依赖于那个。