When we have a final instance variable of a class, is it instantiated for each object created of the class or just created once and referred?
And what is the case if the final variable is a local class variable??
The final modifier simply indicates that the variable can be assigned once and never again. It has no impact on the instantiation; the rules are the same as for normal variables. All the final modifier does is prevent the value being assigned a second time.
Examples below.
private final List myList = new ArrayList();
The list will be instantiated each time this is run, i.e. each time the enclosing class is instantiated.
public void bob() {
final List myList = new ArrayList();
}
The list will be instantiated each time this is run, i.e. each time the method bob is invoked.
private static final List MY_LIST = new ArrayList();
Again, the list will be instantiated each time this is run. As this is also a static field initializer, this code will be run when the class is first loaded. So, for simplistic programs, this will be run once -- in scenarios where multiple class loaders are in play (e.g. app-servers etc), however, this will be run once each time the class is loaded in a new class loader.
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