Showing posts with label init block. Show all posts
Showing posts with label init block. Show all posts

Sunday, 15 May 2011

Order of initialization in java

With so many ways of initializing data fields, it can be quite confusing to give all possible pathways for the construction process. Here is what happens in detail when a constructor is called.
  1. All data fields are initialized to their default value (0, false, or null).
  2. All field initializers and initialization blocks are executed, in the order in which they occur in the class declaration.
  3. If the first line of the constructor calls a second constructor, then the body of the second constructor is executed.
  4. The body of the constructor is executed.
Naturally, it is always a good idea to organize your initialization code so that another programmer could easily understand it without having to be a language lawyer. For example, it would be quite strange and somewhat error prone to have a class whose constructors depend on the order in which the data fields are declared.

Initialization Blocks in java

You have already seen two ways to initialize a data field:
  • By setting a value in a constructor
  • By assigning a value in the declaration
There is actually a third mechanism in Java; it's called an initialization block. Class declarations can contain arbitrary blocks of code. These blocks are executed whenever an object of that class is constructed. For example,

class Employee

{

public Employee(String n, double s)

{

name = n;

salary = s;

}

public Employee()

{

name = "";

salary = 0;

}

. . .

private static int nextId;


private int id;

private String name;

private double salary;

. . .

// object initialization block

{

id = nextId;

nextId++;

}

}



In this example, the id field is initialized in the object initialization block, no matter which constructor is used to construct an object. The initialization block runs first, and then the body of the constructor is executed.

This mechanism is never necessary and is not common. It usually is more straightforward to place the initialization code inside a constructor.


 

Saturday, 14 May 2011

Difference between static and init block

The static block is only loaded when the class object is created by the JVM for the 1st time whereas init {} block is loaded every time class object is created. Also first the static block is loaded then the init block.

public class LoadingBlocks {

static{
System.out.println("Inside static");
}

{
System.out.println("Inside init");
}
public static void main(String args[]){
new LoadingBlocks();
new LoadingBlocks();
new LoadingBlocks();
}
}



Output:

Inside static
Inside init
Inside init
Inside init


So static block is initialized only once, that is it is per class basis, whereas init block is per object basis.