Why must a final variable be initialized before constructor completes?

后端 未结 9 483
暖寄归人
暖寄归人 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).

    0 讨论(0)
  • 2020-12-01 04:20

    Because final prevents you from modifying variables, but it has to be initialized at some point, and the constructors is the right place to do so.

    In your case, it would be called a blank final because it is not initialized when declared.

    0 讨论(0)
  • 2020-12-01 04:21

    A final variable must be initialized at the declaration or in a constructor.

    If it has not been initialized when the constructor returns, it may never be initialized, and may remain an uninitialized variable. The compiler cannot prove it will be initialized, and thus throws an error.

    This Wikipedia excerpt explains it well:

    A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a "blank final" variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared: otherwise, a compile-time error occurs in both cases. (Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.)

    0 讨论(0)
提交回复
热议问题