Java Reference
In-Depth Information
public SampleClass () {
len = 10 ;
table = new int [ len ];
for ( int i = 0 ; i < len ; i ++) table [ i ] = i ;
}
If a constructor begins with a this() call to another constructor, the field
initialization code does not appear in the first constructor. Instead, the initialization
is handled in the constructor invoked by the this() call.
So, if instance fields are initialized in constructor, where are class fields initialized?
These fields are associated with the class, even if no instances of the class are ever
created. This means they need to be initialized even before a constructor is called.
m
g
To support this, javac generates a class initialization method automatically for
every class. Class fields are initialized in the body of this method, which is invoked
exactly once before the class is first used (often when the class is first loaded by the
Java VM.)
As with instance field initialization, class field initialization expressions are inserted
into the class initialization method in the order in which they appear in the source
code. This means that the initialization expression for a class field can use the class
fields declared before it. The class initialization method is an internal method that is
hidden from Java programmers. In the class file, it bears the name <clinit> (and
this method could be seen by, for example, examining the class file with javap —see
Chapter 13 for more details on how to use javap to do this).
O
Initializer blocks
So far, we've seen that objects can be initialized through the initialization expres‐
sions for their fields and by arbitrary code in their constructors. A class has a class
initialization method, which is like a constructor, but we cannot explicitly define the
body of this method as we can for a constructor. Java does allow us to write arbi‐
trary code for the initialization of class fields, however, with a construct known as a
static initializer . A static initializer is simply the keyword static followed by a block
of code in curly braces. A static initializer can appear in a class definition anywhere
a field or method definition can appear. For example, consider the following code
that performs some nontrivial initialization for two class fields:
// We can draw the outline of a circle using trigonometric functions
// Trigonometry is slow, though, so we precompute a bunch of values
public class TrigCircle {
// Here are our static lookup tables and their own initializers
private static final int NUMPTS = 500 ;
private static double sines [] = new double [ NUMPTS ];
private static double cosines [] = new double [ NUMPTS ];
// Here's a static initializer that fills in the arrays
static {
double x = 0.0 ;
Search WWH ::




Custom Search