...
This statement does not apply to instances that use values of static final fields that are initialized at a later stage. Declaring a field to be static final is insufficient to guarantee that it is fully initialized before being read.
...
This noncompliant code example contains an intraclass initialization cycle.:
Code Block | ||
---|---|---|
| ||
public class Cycle { private final int balance; private static final Cycle c = new Cycle(); private static final int deposit = (int) (Math.random() * 100); // Random deposit public Cycle() { balance = deposit - 10; // Subtract processing fee } public static void main(String[] args) { System.out.println("The account balance is: " + c.balance); } } |
...
This compliant solution breaks the interclass cycle by eliminating the dependency of A
on B
.:
Code Block | ||
---|---|---|
| ||
class A { public static final int a = 2; // ... } class B { public static final int b = A.a + 1; // ... } |
...
This code correctly initializes A.a
to 1, using the Oracle JVM, regardless of whether A
or B
is loaded first. However, the JLS does not guarantee that A.a
to be properly initialized. Furthermore, the initialization cycle makes this system harder to maintain and more likely to break in surprising ways when modified.
...