Use of Initializers VS Constructors in Java

Use of Initializers vs Constructors in Java

Static initializers are useful as cletus mentioned and I use them in the same manner. If you have a static variable that is to be initialized when the class is loaded, then a static initializer is the way to go, especially as it allows you to do a complex initialization and still have the static variable be final. This is a big win.

I find "if (someStaticVar == null) // do stuff" to be messy and error prone. If it is initialized statically and declared final, then you avoid the possibility of it being null.

However, I'm confused when you say:

static/instance initializers can be used to set the value of "final"
static/instance variables whereas a constructor cannot

I assume you are saying both:

  • static initializers can be used to set the value of "final" static variables whereas a constructor cannot
  • instance initializers can be used to set the value of "final" instance variables whereas a constructor cannot

and you are correct on the first point, wrong on the second. You can, for example, do this:

class MyClass {
private final int counter;
public MyClass(final int counter) {
this.counter = counter;
}
}

Also, when a lot of code is shared between constructors, one of the best ways to handle this is to chain constructors, providing the default values. This makes is pretty clear what is being done:

class MyClass {
private final int counter;
public MyClass() {
this(0);
}
public MyClass(final int counter) {
this.counter = counter;
}
}

How is an instance initializer different from a constructor?

This seems to explain it well:

Instance initializers are a useful alternative to instance variable
initializers whenever:

  • initializer code must catch exceptions, or

  • perform fancy calculations that can't be expressed with an instance variable initializer. You could, of course, always write such code in
    constructors.


But in a class that had multiple constructors, you would have to repeat the code in each constructor. With an instance initializer, you
can just write the code once, and it will be executed no matter what
constructor is used to create the object. Instance initializers are
also useful in anonymous inner classes, which can't declare any
constructors at all.

From: JavaWorld Object initialization in Java.

static block vs initializer block vs constructor in inheritance

A static block is called once, when the class is loaded and initialized by the JVM. An instance initializer is executed when an instance of the class is constructed, just like a constructor.

Static and Instance initializers are described in the Java Language Specification

static initialization block vs constructor java

Strictly speaking, static initializers are executed, when the class is initialized.

Class loading is a separate step, that happens slightly earlier. Usually a class is loaded and then immediately initialized, so the timing doesn't really matter most of the time. But it is possible to load a class without initializing it (for example by using the three-argument Class.forName() variant).

No matter which way you approach it: a class will always be fully initialized at the time you create an instance of it, so the static block will already have been run at that time.

Static Initializers vs Instance Initializers vs Constructors

The main difference between them is the order they are executed. To illustrate, I will explain them with an example:

public class SomeTest {

static int staticVariable;
int instanceVariable;

// Static initialization block:
static {
System.out.println("Static initialization.");
staticVariable = 5;
}

// Instance initialization block:
{
System.out.println("Instance initialization.");
instanceVariable = 10;
}

// Constructor
public SomeTest() {
System.out.println("Constructor executed.");
}

public static void main(String[] args) {
new SomeTest();
new SomeTest();
}
}

The output will be:

Static initalization.
Instance initialization.
Constructor executed.
Instance initialization.
Constructor executed.

Briefly talking:

  • Static initialization blocks run once the class is loaded by the JVM.
  • Instance initialization blocks run before the constructor each time you instantiate an object.
  • Constructor (obviously) run each time you instantiate an object.

why constructor use, why not always use simple initialization of variables?

Simple definition of constructor:

Special methods that initialize an object of a class. Always and only used together with the new keyword to create an instance of a class.

  1. Has the same name as the name of the class.
  2. Can take one or more arguments.
  3. Has no return value, not even void.
  4. Default constructor takes no parameters.
  5. More than one constructor exist (method overloading).

but why use constructor initialization if it automatically done by
compiler !

Constructors initialize by the compiler (default constructor) if you have not implemented a constructor.

So why do we need to implement a constructor?

  • Its job is to tell all of the local variables their initial values,
    and possibly to start off another method within the class to do
    something more towards the purpose of the class.
  • Depends on what data you have, i.e. what is available.
  • Different ways of creating an object.
  • All class variables have to be initialized with the constructor.

As a example:

  • Consider the Rectangle class in the java.awt package which provides several different constructors, all named Rectangle(), but each with a different number of arguments, or different types of arguments from which the new Rectangle object will get its initial state. Here are the constructor signatures from the java.awt.Rectangle class:

  • public Rectangle()

  • public Rectangle(int width, int height)
  • public Rectangle(int x, int y, int width, int height)
  • public Rectangle(Dimension size)
  • public Rectangle(Point location)
  • public Rectangle(Point location, Dimension size)
  • public Rectangle(Rectangle r)

What if your member variables are private (security reasons)? If you do not want to give other classes to handle member variables, you have to use getters and setters, but in the first place, you can initialize it with a constructor, then you can change it using getters and setters later on when you need to change/update it.

What's the difference between an instance initializer and a constructor?

The code inside the braces with no names will be part of the constructor of the class and be executed before the logic contained in the class constructor.

Quick example:

public class Foo {
{
System.out.println("Before Foo()");
}

public Foo() {
System.out.println("Inside Foo()");
}

{
System.out.println("Not After Foo()");
}
}

Should I initialize variable within constructor or outside constructor

I find the second style (declaration + initialization in one go) superior. Reasons:

  • It makes it clear at a glance how the variable is initialized. Typically, when reading a program and coming across a variable, you'll first go to its declaration (often automatic in IDEs). With style 2, you see the default value right away. With style 1, you need to look at the constructor as well.
  • If you have more than one constructor, you don't have to repeat the initializations (and you cannot forget them).

Of course, if the initialization value is different in different constructors (or even calculated in the constructor), you must do it in the constructor.



Related Topics



Leave a reply



Submit