Why must a final variable be initialized before constructor completes?

后端 未结 9 506
暖寄归人
暖寄归人 2020-12-01 03:38

Why must a final variable be initialized before constructor completes?

public class Ex
{
  final int q;
}

When I compile this code I get er

9条回答
  •  星月不相逢
    2020-12-01 04:16

    The official reason is that it is defined by the Java Language Specification 8.3.1.2:

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

    A blank final is a final variable whose declaration lacks an initializer (i.e. what you describe).

提交回复
热议问题