Default constructor vs. inline field initialization

Initialisers are executed before constructor bodies. (Which has implications if you have both initialisers and constructors, the constructor code executes second and overrides an initialised value)

Initialisers are good when you always need the same initial value (like in your example, an array of given size, or integer of specific value), but it can work in your favour or against you:

If you have many constructors that initialise variables differently (i.e. with different values), then initialisers are useless because the changes will be overridden, and wasteful.

On the other hand, if you have many constructors that initialise with the same value then you can save lines of code (and make your code slightly more maintainable) by keeping initialisation in one place.

Like Michael said, there’s a matter of taste involved as well – you might like to keep code in one place. Although if you have many constructors your code isn’t in one place in any case, so I would favour initialisers.

Leave a Comment