Java Reference
In-Depth Information
Invocation of certain reflective methods in class
Class
and in package
java.lang.reflect
also
causes class or interface initialization.
A class or interface will not be initialized under any other circumstance.
The intent is that a class or interface type has a set of initializers that put it in a consistent
state, and that this state is the first state that is observed by other classes. The static ini-
tializers and class variable initializers are executed in textual order, and may not refer to
class variables declared in the class whose declarations appear textually after the use, even
though these class variables are in scope (§
8.3.2.3
). This restriction is designed to detect,
at compile time, most circular or otherwise malformed initializations.
where the value of a class variable can be observed when it still has its initial default
value, before its initializing expression is evaluated, but such examples are rare in practice.
full power of the Java programming language is available in these initializers; programmers
must exercise some care. This power places an extra burden on code generators, but this
burden would arise in any case because the Java programming language is concurrent
Example 12.4.1-1. Superclasses Are Initialized Before Subclasses
class Super {
static { System.out.print("Super "); }
}
class One {
static { System.out.print("One "); }
}
class Two extends Super {
static { System.out.print("Two "); }
}
class Test {
public static void main(String[] args) {
One o = null;
Two t = new Two();
System.out.println((Object)o == (Object)t);
}
}
This program produces the output: