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.
In a Java class with static instance fields, is the constructor called every time
Share
Don’t. Never initialize static fields inside a constructor.
staticfields 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 initializerblock to initialize your static fields, or just initialize them at the place of declaration.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, onclass name, in which case, the change will be effected for all the instances. So, the constructor will not be invoked, whenever you accessstatic field.In fact, even when you access instance field, constructor is not invoked every time. Constructor is used to
initializethestateof the newly created instance once. And for further access and modification of that field,constructorwon’t be invoked.So, a constructor has precisely no role to play whenever you want to access any fields of your class.