Setting a static final variable in the constructor

what i basically want:

public class Test { private static final Integer a; public Test(Integer a) { this.a = a; } 

}

This clearly does not work, because the second instantiated instance will try to override the final variable. So, is there a way to provide all instances with the same immutable value through the constructor?

+4
source share
2 answers

Static endpoints should be initialized in a static context, not in instances.

One parameter 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 the static method

 private static int getA() { return FileConfig.getInstance().getA(); } private static final Integer a=getA(); 

In closure, static instance initialization does not belong to instance constructors.

If the configuration values ​​sometimes change, it just doesn't make sense to store the value of a in a static final variable. If you want to create each instance with constant a in the constructor, what is the purpose of the static field in the first place? Somehow, when you call the constructor for the first time, you are passing a value from somewhere . If a value deserves to be static and final, you can get it from a static initializer. If the configuration is not single, but each instance always produces the same value of a, you can easily do a = new FileConfig().getA(); .

In addition, you can make the value non-final, and be sure that, since you always put the same value a , the static variable will not change.

However, you can make a final class instance variable specified in the constructor.

+11
source

So, is there a way to provide all instances with the same immutable value through the constructor?

I assume that you want to assign the value a when creating an object of type Test , but not when creating any subsequent instance. In this case, you cannot declare it final . a will be empty first, the constructor must check if it is null and assign a value to it in this case.

But I urge you to take a look at the design, especially why the caller must provide meaning. Is it not counter-intuitive that after creating the second object Test Test.a does not change in the following case?

 // assume this is the first `Test` object created: Test t = new Test(5); // Test.a is 5 Test t = new Test(6); // Test.a is *still* 5 
+2
source

Source: https://habr.com/ru/post/1441683/