Maria Gaitani wrote:
Thank you both very much for your reply !
May I ask why is there a need for such a block since the same thing
happens if that block of code would be executed again only once if it was
in the constructor of the class.
No, it would be executed once for every instance of that class that was
created.
HelloWorld hw1 = new HelloWorld();
HelloWorld hw2 = new HelloWorld();
Now you've called loadLibrary() twice. Contrariwise, if you never create an
instance of the class then the library is never loaded.
Some classes are what we call "utility" classes: they have only static
members, and there is no way to create an instance of the class(*). For
such classes, a static{} clause is really the only place to do any
initialisation work that may be required.
Some classes are what we call "singletons": they are designed so that only
one instance can be created, and a reference to this instance can be
obtained by calling a static method (often called getInstance()). In this
case it may be a question of taste whether initialisation code is contained
in a static{} clause or in the constructor.
Most classes however are designed so that many instances can be created. In
this case code which should only be executed once should normally go in a
static{} clause (or be called from there), and code that should be called
for each instance belongs in (or gets called from) a constructor.
(*) If a class has a default constructor so:
private Foo() {}
there is no way to construct an instance from outside the class.
HTH
--
Chris Gray
ch***@kiffer.eunet.be
/k/ Embedded Java Solutions