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

Discussion in 'Java' started by Saurabh, May 29, 2004.

  1. Saurabh

    Saurabh Guest

    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
     
    Saurabh, May 29, 2004
    #1
    1. Advertising

  2. Saurabh

    Chris Smith Guest

    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
     
    Chris Smith, May 29, 2004
    #2
    1. Advertising

  3. Saurabh

    Tony Morris Guest

    > 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)
     
    Tony Morris, May 29, 2004
    #3
  4. Saurabh

    Saurabh Guest

    Re: Difference between putting code in constructor and putting codein static{}

    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
     
    Saurabh, May 29, 2004
    #4
  5. Saurabh

    Chris Smith Guest

    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
     
    Chris Smith, May 29, 2004
    #5
  6. Saurabh

    P.Hill Guest

    Re: Difference between putting code in constructor and putting codein static{}

    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.
     
    P.Hill, May 30, 2004
    #6
  7. Saurabh

    Chris Smith Guest

    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
     
    Chris Smith, May 30, 2004
    #7
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page