Java Reference
In-Depth Information
even though the constructor (§ 8.8 ) for Test refers to the field k that is declared three
lines later.
The restrictions above are designed to catch, at compile time, circular or otherwise
malformed initializations. Thus, both:
class Z {
static int i = j + 2;
static int j = 4;
}
and:
class Z {
static { i = j + 2; }
static int i, j;
static { j = 4; }
}
result in compile-time errors. Accesses by methods are not checked in this way, so:
Click here to view code image
class Z {
static int peek() { return j; }
static int i = peek();
static int j = 1;
}
class Test {
public static void main(String[] args) {
System.out.println(Z.i);
}
}
produces the output:
0
because the variable initializer for i uses the class method peek to access the value of
the variable j before j has been initialized by its variable initializer, at which point it
still has its default value (§ 4.12.5 ).
A more elaborate example is:
Click here to view code image
class UseBeforeDeclaration {
static {
x = 100;
Search WWH ::




Custom Search