This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When to use Static initial block?

 
Rakesh shankar
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Can we use constructor to initialize static members of a class.
If this is possible then what is the use of static initial block.

Can anyone explain me in which scenario we go for static initial block??

Thanks in advance..
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rakesh Ss wrote:... Can we use constructor to initialize static members of a class.
If this is possible then what is the use of static initial block...

A constructor is only called when an instance is being created. So for static (class) members to be properly initialized, a constructor will not work, and a static block might be required instead.
 
Stephan van Hulst
Bartender
Pie
Posts: 5387
52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Except if the static fields are only used through instance methods, then you can do lazy initializing through the constructor.
 
Greg Brannon
Bartender
Posts: 563
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're asking about a "static initialization block," right?
 
Lucky J Verma
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static blocks -are static ,they run when class is loaded and not associated with any instances /objects of class or constructor(constructor constructs an object)


Stephen -

"Except if the static fields are only used through instance methods, then you can do lazy initializing through the constructor."

I am really interested in the exceptional case that you mentioned.Can you please provide some examples to explain better.

Thanks.
 
Stephan van Hulst
Bartender
Pie
Posts: 5387
52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Here is such an example. Let's say Expensive objects are very expensive to create. You don't want to create them until you really have to. If the Expensive object is only used by instance methods, like plus(), you can avoid creating one until the first instance of Test is created. This way, if a program only needs the help() method, it can avoid creating a Test (and thus an Expensive) altogether.

This is a rare situation, but it's just an example.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic