| Author |
When to use Static initial block?
|
Rakesh shankar
Greenhorn
Joined: Nov 12, 2010
Posts: 13
|
|
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
Joined: Aug 31, 2004
Posts: 11343
|
|
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
Joined: Sep 20, 2010
Posts: 3065
|
|
|
Except if the static fields are only used through instance methods, then you can do lazy initializing through the constructor.
|
 |
Greg Brannon
Bartender
Joined: Oct 24, 2010
Posts: 530
|
|
|
You're asking about a "static initialization block," right?
|
Learning Java using Eclipse on OpenSUSE 11.2
Linux user#: 501795
|
 |
Lucky J Verma
Ranch Hand
Joined: Apr 11, 2007
Posts: 277
|
|
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
Joined: Sep 20, 2010
Posts: 3065
|
|
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.
|
 |
 |
|
|
subject: When to use Static initial block?
|
|
|