In Java, we use the static initialization block:
private static final ApiKey API_KEY;
static {
API_KEY = new ApiKey();
}
I was wondering that
Thanks in advance.
Static variables are initialized only once. Compiler persist the variable till the end of the program. Static variable can be defined inside or outside the function. They are local to the block.
Statics tend to make writing good tests harder. If you ever find you want to start modifying static state then you probably need to look at the design again. Consider looking at Google Guice and its very nice Singleton implementation.
The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. Note: We use Initializer Block in Java if we want to execute a fragment of code for every object which is seen widely in enterprising industries in development.
There can be multiple static initialization blocks in a class that is called in the order they appear in the program.
You could avoid using a static initializer block completely by using the following code:
private static final ApiKey API_KEY = new ApiKey();
or
private static final ApiKey API_KEY = createNewApiKey();
if the API key creation requires more than just a constructor call. That makes the code more readable, IMHO. But it doesn't matter much.
The static initializer is useful when two static fields depend on the same initialization code:
static {
// compute some values
A = somePartOfTheComputedValues();
B = someOtherPartOfTheComputedValues();
}
But even then, A and B could perhaps be refactored into a single object, which would be created in a single method.
I like using enums whenever possible.
Instead of
class ApiKey {
private static final ApiKey API_KEY;
static {
API_KEY = new ApiKey();
}
I would write
enum ApiKey {
INSTANCE;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With