Initialize a static final field in the constructor

2019-01-10 08:17发布

public class A 
{    
    private static final int x;

    public A() 
    {
        x = 5;
    }
}
  • final means the variable can only be assigned once (in the constructor).
  • static means it's a class instance.

I can't see why this is prohibited. Where do those keywords interfere with each other?

7条回答
对你真心纯属浪费
2楼-- · 2019-01-10 08:45

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;
    }
}
查看更多
登录 后发表回答