Java - final variables

前端 未结 7 1275
爱一瞬间的悲伤
爱一瞬间的悲伤 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

    You should initialize a static final variable either in a static initializer, or directly. So either

    static final JButton button = new JButton();
    

    or

    static final JButton button;
    
    static {
      button = new JButton();
    }
    

    The Java language specification has some more documentation about it: the section about final variables specifies why you get the compile error:

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

    and chapter 16 talks about the definite assignment

提交回复
热议问题