Sunday, 15 May 2011

Explicit or direct Field Initialization in java

Because you can overload the constructor methods in a class, you can obviously build in many ways to set the initial state of the instance fields of your classes. It is always a good idea to make sure that, regardless of the constructor call, every instance field is set to something meaningful.
You can simply assign a value to any field in the class definition. For example,
class Employee

{

. . .

private String name = "";

}



This assignment is carried out before the constructor executes. This syntax is particularly useful if all constructors of a class need to set a particular instance field to the same value.

The initialization value doesn't have to be a constant value. Here is an example in which a field is initialized with a method call. Consider an Employee class where each employee has an id field. You can initialize it as follows:

class Employee

{

. . .

static int assignId()

{

int r = nextId;

nextId++;

return r;

}

. . .

private int id = assignId();

}



See cpp vs java in case of direct field initialization.

No comments:

Post a Comment