Initialize a static final field in the constructor

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

    Think about what happens the second time you instantiate an object. It tries to set it AGAIN, which is expressly prohibited by being a static final. It can only be set one time for the entire class, not instance.

    You should set the value when you declare it

    private static final x=5;
    

    If you need additional logic, or more complex instantiation, this can be done in a static initializer block.

提交回复
热议问题