Initialize a static final field in the constructor

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

    Think about it. You could do this with your code:

    A a = new A();
    A b = new A(); // Wrong... x is already initialised
    

    The correct ways to initialise x are:

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

    or

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

提交回复
热议问题