Monday, May 16, 2011

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.


 

No comments:

Post a Comment

Chitika