Java Reference
In-Depth Information
init , the difference is that such a method would not be recognized as
construction code and could not, for example, assign values to blank fi-
nal fields. Initialization is the purpose of having initialization blocks, but
in practice you can make it do anythingthe compiler won't check what
it does. Spreading initialization code all through a class is not a good
design, and initialization blocks should be used judiciously, when they
express something that cannot easily be done by constructors alone.
2.5.3. Static Initialization
The static fields of a class can have initializers as we have already seen.
But in addition we can perform more complex static initialization in a
static initialization block. A static initialization block is much like a non-
static initialization block except it is declared static , can only refer to
static members of the class, and cannot throw any checked exceptions.
For example, creating a static array and initializing its elements some-
times must be done with executable statements. Here is example code
to initialize a small array of prime numbers:
class Primes {
static int[] knownPrimes = new int[4];
static {
knownPrimes[0] = 2;
for (int i = 1; i < knownPrimes.length; i++)
knownPrimes[i] = nextPrime();
}
// declaration of nextPrime ...
}
The order of initialization within a class is first-to-lasteach field initializer
or initialization block is executed before the next one, from the begin-
ning of the source to the end. The static initializers are executed after
the class is loaded, before it is actually used (see " Preparing a Class for
Use " on page 441 ) . With this guarantee, our static block in the example
is assured that the knownPrimes array is already created before the initial-
 
Search WWH ::




Custom Search