空白决赛本地 vs 空白决赛场地

Blank Final Local vs Blank Final Field

为什么初始化局部 final 变量不编译?此行为似乎与 final 未初始化 a 的字段形成了编译错误。

class Test {

    final Test test1; // doesn't compile

    public Test(){
        final Test test2; // does compile
    }
}

这个选择背后的逻辑是什么?

这来自于JLS的规则。

来自4.12.4

It is a compile-time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment.

来自4.12.5

A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16).

来自8.3.1.2

A blank final instance variable must be definitely assigned (§16.9) at the end of every constructor (§8.8) of the class in which it is declared; otherwise a compile-time error occurs.

所以技术上的原因是因为它没有被禁止。字段必须在构造对象时初始化。局部变量只需要在使用前进行初始化。

其背后的逻辑是,class 变量可能被另一个对象引用,因此需要在另一个对象可能对它进行初始化引用时对其进行初始化。局部变量不会逃脱它的作用域,因此编译器可以保证它不会被引用,只要它不在该作用域内使用。