Initialize a static final field in the constructor

后端 未结 8 581
执念已碎
执念已碎 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:43

    static final variables are initialized when the class is loaded. The constructor may be called much later, or not at all. Also, the constructor will be called multiple times (with each new object ), so the field could no longer be final.

    If you need custom logic to initialize your static final field, put that in a static block

提交回复
热议问题