Initialize final variable before constructor in Java

后端 未结 9 1740
旧时难觅i
旧时难觅i 2020-12-03 09:00

Is there a solution to use a final variable in a Java constructor? The problem is that if I initialize a final field like:

private final String name = \"a na         


        
9条回答
  •  误落风尘
    2020-12-03 09:27

    I cannot use it in the constructor, while java first runs the constructor an then the fields...

    This is not correct, fields are evaluated first, otherwise you couldn't access any default values of members in your constructors, since they would not be initialized. This does work:

    public class A {
        protected int member = 1;
        public A() {
            System.out.println(member);
        }
    }
    

    The keyword final merely marks the member constant, it is treated as any other member otherwise.

    EDIT: Are you trying to set the value in the constructor? That wouldn't work, since the member is immutable if defined as final.

提交回复
热议问题