Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This compliant solution breaks the interclass inter-class cycle by eliminating one of the dependenciesthe dependency of A on B.

Code Block
bgColor#ccccff
class A {
  public static final int a = 2;
  // ...
}

// class B unchanged: {
  public static final int b = A.a + 1;
  // ...
}

With the cycle broken, the initial values will always be A.a = 2 and B.b = 3, regardless of initialization order.

Noncompliant Code Example

This The programmer in this noncompliant code example tries attempts to initialize a static variable in one class using a static method in a second class, but that method in turn relies on a static method in the first class.

...

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 sytem system harder to maintain, and more likely to break in surprising ways when modified.

...

 

...

Rule 01. : Declarations and Initialization (DCL)      Rule 01. : Declarations and Initialization (DCL)