Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Initialization blocks and constructors

 
Wilson Yang
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An instance field can be initialized in three places:
1.right after the declaration;
2.in initialization block;
3.in constructors;
Does anybody know when to use which initialization method?
 
Campbell Ritchie
Sheriff
Pie
Posts: 50277
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Depends whether you want the initial value to be the same for all objects of that class or not.

If you want the initial value set differently (from outside) for each instance: constructor.
If you want it set the same each time, or worked out from inside the class, use an initialiser or at the same place as declaration.
You could set up every instance field in the constructor if you wish.

Static fields are different; they are often best set up in an initialiser (static) or when declared rather than in the constructor.

Just as important as where the fields are initialised is whether they are initialised; forgetting to initialise a field by the time the constructor completes is a sure-fire recipe for mysterious NullPointerExceptions 20 minutes later.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) If the variable can't be initialized without information from the outside world (ie a parameter passed to the constructor) then you would need use the Constructor.

2) If the variable can be initialized without help from the outside world, but is a complex (multi-line) initialization then you would put it inside an initializor block (for example, you have a HashMap with several entries added to it).

3) If the variable can be initialized without help from the outside world, and the initialization is simple (a single line of code) then you can do it when it is declared.

You can move any initialization 'up' that chain (ie anything that can be done in 3) can be done in 2) and anything that can be done in 2) can be done in 1)), but can't move down the chain.

If you have a choice, then it comes mostly to personal preferences. If I can, I like to initialize on the same line as the declaration because it lends itself to self-documentation (as far as knowing what gets stored where). If not then I like to initialize in the Constructor. I don't like initializer blocks because they are just easy to look past, but that is just me.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic