In a Java class with static instance fields, is the constructor called every time the fields are accessed, or only on the first access? I initialize the static fields in the constructor, and was wondering if this would cause a slow down because the fields are initialized on every access.
解决方案
I initialize the static fields in the constructor,
Don't. Never initialize static fields inside a constructor. static fields are not something associated with any instance of a class. It is bound to class. There is only single copy of that variable, that is accessed accross all the instances. So, if you are initializing it in constructor, then every time you create an instance, that field will be re-initialized for every other instance.
You should use static initializer block to initialize your static fields, or just initialize them at the place of declaration.
class Demo {
private static int x; // Either initialize it here.
static { // Or use static initializer block
x = 10;
}
}
with static instance fields, is the constructor called every time the fields are accessed,
No. , static fields are accessed on class. They are loaded and initialized when the class is loaded. And then you can modify it later on, on class name, in which case, the change will be effected for all the instances. So, the constructor will not be invoked, whenever you access static field.
In fact, even when you access instance field, constructor is not invoked every time. Constructor is used to initialize the state of the newly created instance once. And for further access and modification of that field, constructor won't be invoked.
So, a constructor has precisely no role to play whenever you want to access any fields of your class.