Java - final variables

前端 未结 7 1158
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-16 01:43

I know that once a final variable has a value assigned to it, it cannot be changed. However I just have a couple of questions regarding this:

  • When I have a

7条回答
  •  有刺的猬
    2020-12-16 01:59

    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.

    Types of Final Variables

    1) INSTANCE 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; otherwise, a compile-time error occurs

    2) STATIC FINAL VARIABLE

    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 the cases the intention is to avoid using the final variable before it is initialized.

    So in your case it must be initialized via the static initializer block which initializes when the class is loaded.

    Ref : http://en.wikipedia.org/wiki/Final_(Java)

提交回复
热议问题