Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Difference between putting code in constructor and putting code in static{}

Reply
Thread Tools

Difference between putting code in constructor and putting code in static{}

 
 
Saurabh
Guest
Posts: n/a
 
      05-29-2004
Hi,

Can somebody please help me with this? I am trying to figure out the
difference between this piece of code:

class Person {
private final Date birthDate;

public Person(Date birthDate) {
this.birthDate = birthDate;
}

private static final Date BOOM_START;

static {
Calendar gmtCal =
Calendar.getInstance(TimeZone.getTimeZone("GMT"));
gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
BOOM_START = gmtCal.getTime();
}

public boolean isBabyBoomer() {
..
}
}

and this:
class Person {
private final Date birthDate;

public Person(Date birthDate) {
this.birthDate = birthDate;
Calendar gmtCal =
Calendar.getInstance(TimeZone.getTimeZone("GMT"));
gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
BOOM_START = gmtCal.getTime();
}

private static final Date BOOM_START;

public boolean isBabyBoomer() {
..
}
}

The code example is a truncated version of some code from Effective
Java. I have been trying to figure out if there would be any
difference between the two. And why you would want to put some code in
static{} instead of contructors.

Thanks
Saurabh
 
Reply With Quote
 
 
 
 
Chris Smith
Guest
Posts: n/a
 
      05-29-2004
Saurabh wrote:
> Can somebody please help me with this? I am trying to figure out the
> difference between this piece of code:


> static {
> Calendar gmtCal =
> Calendar.getInstance(TimeZone.getTimeZone("GMT"));
> gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
> BOOM_START = gmtCal.getTime();
> }


> and this:


> public Person(Date birthDate) {
> this.birthDate = birthDate;
> Calendar gmtCal =
> Calendar.getInstance(TimeZone.getTimeZone("GMT"));
> gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
> BOOM_START = gmtCal.getTime();
> }


Okay...

> The code example is a truncated version of some code from Effective
> Java. I have been trying to figure out if there would be any
> difference between the two. And why you would want to put some code in
> static{} instead of contructors.


The most obvious difference is that the first example sets BOOM_START
the first time the class is loaded, whereas the second tries to set it
every time you create an instance of the class. The latter will almost
certainly fail to compile, since BOOM_START is declared final. The
former might or might not work (don't have the time to check the JLS
right now, but it is definitely assigned once in a static initializer,
which may be good enough to satisfy the requirements of a final field).

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
Reply With Quote
 
 
 
 
Tony Morris
Guest
Posts: n/a
 
      05-29-2004
> The code example is a truncated version of some code from Effective
> Java. I have been trying to figure out if there would be any
> difference between the two. And why you would want to put some code in
> static{} instead of contructors.
>
> Thanks
> Saurabh


There is a huge difference.
A static initializer executes at class load time, meaning it executes once
for each time the class is loaded (once per class loader).
A constructor executes each time an object is instantiated.
new TheObject(); // for example

Perhaps you want to consider the difference between an initializer
(non-static) and a constructor.

--
Tony Morris
(BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
Software Engineer
IBM Australia - Tivoli Security Software
(2003 VTR1000F)


 
Reply With Quote
 
Saurabh
Guest
Posts: n/a
 
      05-29-2004
Tony Morris wrote:
> There is a huge difference.
> A static initializer executes at class load time, meaning it executes once
> for each time the class is loaded (once per class loader).
> A constructor executes each time an object is instantiated.
> new TheObject(); // for example
>
> Perhaps you want to consider the difference between an initializer
> (non-static) and a constructor.


Ok - I have some more (maybe basic) questions.

I am confused between class loader and instantiation - wont both me
dependent on each other. Actually class loading might not lead to
instantiation but instantiation will surely lead to class loading. Would
this statement be correct? Is there anything that you would consider as
a good read on this topic?

And considering initializer is non-static - what would be the difference
there? (similar to loading vs. instantiation??)

Thanks
Saurabh
 
Reply With Quote
 
Chris Smith
Guest
Posts: n/a
 
      05-29-2004
Saurabh wrote:
> I am confused between class loader and instantiation - wont both me
> dependent on each other. Actually class loading might not lead to
> instantiation but instantiation will surely lead to class loading. Would
> this statement be correct? Is there anything that you would consider as
> a good read on this topic?


Right. A class *may* be initialized because an object is created, but
it will also be initialized if a static method is called or a static
field is accessed, or even just because is was loaded by Class.forName
or a class literal expression. So class initialization does not imply
that an object is being created.

Also right that creating an object does imply that the class is
initialized. However, the class is only initialized the *first* time an
object is created. Future objects of that class will still have their
instance initializers and constructors run, but the static initializer
block will *not* be repeated.

> And considering initializer is non-static - what would be the difference
> there? (similar to loading vs. instantiation??)


The difference between an instance initializer block and a constructor
is much more subtle. Both are places to define code that gets run when
an object of a class is created. The differences are:

1. The constructor can define parameters to pass information into the
class; instance initializers don't have access to these parameters.

2. You can provide alternative constructors to allow the object to be
created in different ways. If you define multiple instance
initializers, then it *both* are run, not *either*. Speaking of which,
if you declare both a constructor and instance initializers, then
constructor *and* the instance initializers are all run.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
Reply With Quote
 
P.Hill
Guest
Posts: n/a
 
      05-30-2004
Chris Smith wrote:
> 1. The constructor can define parameters [...]
>
> 2. You can provide alternative constructors [...]


3. Constructors can throw exceptions. This provides another mechanism
of communication back to the caller about the behaviour of the code.
Instance initializers can not throw an exception. I'll admit this is not
a very common construct, but it has it' uses.

 
Reply With Quote
 
Chris Smith
Guest
Posts: n/a
 
      05-30-2004
P.Hill wrote:
> 3. Constructors can throw exceptions. This provides another mechanism
> of communication back to the caller about the behaviour of the code.
> Instance initializers can not throw an exception. I'll admit this is not
> a very common construct, but it has it' uses.


Not exactly true. Instance initializers can throw any exception that
can be thrown by all constructors. That always includes Error and
RuntimeException and their subclasses, and can include any other
exceptions that are declared explicitly in the throws clause of
constructors. For example, the following code compiles fine:

import java.io.IOException;

public class Test
{
{
if (true) throw new IOException();
}

public Test() throws IOException
{
}
}

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
A constructor calling another constructor (default constructor)? Generic Usenet Account C++ 10 11-28-2007 04:12 AM
what is the difference between code inside a <script> tag and code in the code-behind file? keithb ASP .Net 1 03-29-2006 01:00 AM
difference between a namespace and class with just default constructor Youssef Mesri C++ 15 01-19-2006 10:31 AM
Difference between bin and obj directories and difference between project references and dll references jakk ASP .Net 4 03-22-2005 09:23 PM
difference between constructor and Page_Init() Christian ASP .Net 0 07-16-2003 10:25 PM



Advertisments