java - Default constructor vs. inline field initialization -
what's difference between default constructor , initializing object's fields directly?
what reasons there prefer 1 of following examples on other?
example 1
public class foo { private int x = 5; private string[] y = new string[10]; }
example 2
public class foo { private int x; private string[] y; public foo() { x = 5; y = new string[10]; } }
initialisers executed before constructor bodies. (which has implications if have both initialisers , constructors, constructor code executes second , overrides initialised value)
initialisers when need same initial value (like in example, array of given size, or integer of specific value), can work in favour or against you:
if have many constructors initialise variables differently (i.e. different values), initialisers useless because changes overridden, , wasteful.
on other hand, if have many constructors initialise same value can save lines of code (and make code more maintainable) keeping initialisation in 1 place.
like michael said, there's matter of taste involved - might keep code in 1 place. although if have many constructors code isn't in 1 place in case, favour initialisers.
Comments
Post a Comment