Setting a static final variable in constructor
constructor, final, java, static
Solution
Static final values should be initialized in a static context, not by instances.
One options is to set the value in the declaration:
private static final Integer a=FileConfig.getInstance().getA();
Each class can have a static {} block where code is called to initialize the static parts of the class.
static {
a = FileConfig.getInstance().getA();
}
Finally, you can set the value from a static method
private static int getA() {
return FileConfig.getInstance().getA();
}
private static final Integer a=getA();
In closure, static instance initialization does not belong in instance constructors.
If the configuration values change sometimes, there is simply no reason to store the value a in a static final variable. If you want to create each instance with the constant a in the constructor, what is the purpose of a static field in the first place? Somehow, when you call the constructor for the first time, you are passing in a value from somewhere. If the value deserves to be static and final, you can acquire it from within the static initializer. If the configuration is not a singleton, but every instance always produces the same value of a, you could easily do `a = new FileConfig().getA();`.
Other than that, you could make the value non-final, and rest assured that since you always put in the same value of `a`, the static variable will not change.
Still, you could make `a` a final instance variable of the class, set in the constructor.
Problem
what i basicly want is this: ``` public class Test { private static final Integer a; public Test(Integer a) { this.a = a; } ``` } This obviously doesn't work, cause the 2nd created instance would try to override the final variable. So is there a way to give all the instances the same immutable value via the constructor?