Initialize a static final field in the constructor

后端 未结 8 611
执念已碎
执念已碎 2020-11-30 22:57
public class A 
{    
    private static final int x;

    public A() 
    {
        x = 5;
    }
}
  • final means the variable can
8条回答
  •  情书的邮戳
    2020-11-30 23:27

    A constructor will be called each time an instance of the class is created. Thus, the above code means that the value of x will be re-initialized each time an instance is created. But because the variable is declared final (and static), you can only do this

    class A {    
        private static final int x;
    
        static {
            x = 5;
        }
    }
    

    But, if you remove static, you are allowed to do this:

    class A {    
        private final int x;
    
        public A() {
            x = 5;
        }
    }
    

    OR this:

    class A {    
        private final int x;
    
        {
            x = 5;
        }
    }
    

提交回复
热议问题