...
This noncompliant code example contrives to calculate the account balance by subtracting the processing fee from the deposited amount, but fails to do so. The Cycle
class object c
is instantiated before the deposit
field gets initialized. As a result, the constructor Cycle()
is invoked which computes the balance based on the initial value of deposit
(0) rather than the random value. As a result, the balance always remains -10
.
Code Block | ||
---|---|---|
| ||
public class Cycle {
private static final Cycle c = new Cycle();
private final int balance;
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);
}
}
|
Wiki Markup |
---|
According to the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\], section 12.4 "Initialization of Classes and Interfaces": |
...
Wiki Markup |
---|
This statement asserts that the presence of a {{static}} field triggers the initialization of a class, however, in this example, a recursive attempt is being made to initialize the class already. Because such recursive attempts are ignored by the JVM, the default value of {{deposit}} is {{0}} during the initialization. \[[Bloch 05|AA. Java References#Bloch 05]\] |
...
bgColor | #FFcccc |
---|
...
Compliant Solution
This compliant solution changes the initialization order of the class Cycle
so that the fields meant to be used in computations get duly initialized. As initialization cycles can become insidious when many classes are involved, proper care must be taken to inspect the control flow.
...