You initialize a static field either by supplying an initial value or by using a static initialization block. You have already seen the first mechanism:
static int nextId = 1;
If the static fields of your class require complex initialization code, use a static initialization block.
Place the code inside a block and tag it with the keyword static. Here is an example. We want the employee ID numbers to start at a random integer less than 10,000.
// static initialization block
static
{
Random generator = new Random();
nextId = generator.nextInt(10000);
}
Static initialization occurs when the class is first loaded. Like instance fields, static fields are 0, false, or null unless you explicitly set them to another value. All static field initializers and static initialization blocks are executed in the order in which they occur in the class declaration.
No comments:
Post a Comment