Tuesday, 15 October 2013

Initializing fields in Java

I only recently found out that the topic of initializing class and instance fields is not as small as I thought. I wish I was thoroughly introduced to this from the early beginning. Let's have a look at it.

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