无法在构造函数内部调用的方法中为最终变量赋值
class A {
private final int t1;
private final int t2;
public A(int c1, int c2) {
t1 = c1;
initT2(c2);
}
private void initT2 (int c2) {
try {
t2 = c2;
} catch (...) {}
}
}
t1 被初始化但 t2 没有。Cannot assign a value to final variable 's3Client'是错误。
如果我initT2在构造函数内移动函数的主体,它就可以工作。从构造函数内部调用它时,为什么它不能在构造函数外部工作?
回答
这只是 Java 的一条规则 - 您可以在构造函数内部、在声明它时或在静态初始化程序中初始化最终变量,但不能在构造函数外部的代码(例如 initT2 方法)中初始化。
- @FerociousPup but that method could be called outside of the constructor, the compiler isn't smart enough to know its only called in the constructor