The most straightforward way to initialize a field, whether static or not, is to simply assign it some value. There may be times, however, when the value of your field needs some extra steps to compute. There are three approaches here: firstly, you can initialize the field in the constructor; secondly, you can compute the field value in a method that then returns that value to the field, like below:
Field initialization
And thirdly, the cool -yet possibly confusing- approach: (static) initialization blocks! The following is a valid Java program:
Initialization blocks
All of the methods and blocks described above are executed before the constructor (the blocks are actually added to the top of all the constructors), with static field initialization running before instance field initialization. The below code will illustrate the order in which initialization occurs:
Field initialization
With output:
Field initialization
You can find out more on the topic from Oracle's article. And, although not quite on the same topic, this is where I first saw static blocks: What is called before main?
One last thing to mention: if you don't initialize your fields, they will be assigned a default value (depending on type), with the exception of final fields, which need to be initialized by the coder.
No comments:
Post a Comment