• Post Reply Bookmark Topic Watch Topic
  • New Topic

instance initialization blocks doubt  RSS feed

 
Ranch Hand
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why do we have instance initialization block to initialize a member variable Z ? Why not initialize the member Z in the class itself ?
 
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perhaps the initializer can throw an exception-- you then need the block so you can include a "try" to catch it.
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or the calculation of the value might be too complex to want to put on a single line.
 
Rahul Sudip Bose
Ranch Hand
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest Friedman-Hill wrote:Perhaps the initializer can throw an exception-- you then need the block so you can include a "try" to catch it.


I am not clear about this. Can you give me sample code which illustrates this ? Do you use such init blocks often in your code ?
 
Rahul Sudip Bose
Ranch Hand
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote:Or the calculation of the value might be too complex to want to put on a single line.

So, that means we split our big calculation into steps which are enclosed in neat little init blocks (for ease of reading) ?
 
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Probably better to initialise those fields in the constructor, using (private or final) methods for the values which take a long time to calculate.
 
Ranch Hand
Posts: 227
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instance initializers are invaluable in case of anonymous inner classes, when one wants to intialize a property (for ex., a DateFormat or Pattern).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!