Java Reference
In-Depth Information
Using Initialization Blocks
An initialization block is a block of code between braces that is executed before an object of the class is
created. There are two kinds of initialization blocks. A static initialization block is a block defined using the
keyword, static , and that is executed once when the class is loaded and can only initialize static data
members of the class. A non-static initialization block is executed for each object that is created and thus can
initialize instance variables in a class. This is easiest to understand by considering specific code.
Try It Out - Using an Initialization Block
Let's define a simple class with a static initialization block first of all:
class TryInitialization {
static int[] values = new int[10]; // Static array member
// Initialization block
static {
System.out.println("Running initialization block.");
for(int i=0; i<values.length; i++)
values[i] = (int)(100.0*Math.random());
}
// List values in the array for an object
void listValues() {
System.out.println(); // Start a new line
for(int i=0; i<values.length; i++)
System.out.print(" " + values[i]); // Display values
System.out.println(); // Start a new line
}
public static void main(String[] args) {
TryInitialization example = new TryInitialization();
System.out.println("\nFirst object:");
example.listValues();
example = new TryInitialization();
System.out.println("\nSecond object:");
example.listValues();
}
}
When you compile and run this you will get identical sets of values for the two objects - as might be
expected since the values array is static:
Running initialization block.
First object:
40 97 88 63 58 48 84 5 32 67
Second object:
40 97 88 63 58 48 84 5 32 67
Search WWH ::




Custom Search