...
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 Random deposit public Cycle(){ balance = deposit - 10; //subtract Subtract processing fee } public static void main(String[] args) { System.out.println("The account balance is: " + c.balance); } } |
...
Code Block | ||
---|---|---|
| ||
public class Cycle { private final int balance; private static final int deposit = (int) (Math.random() * 100); //random Random deposit private static final Cycle c = new Cycle(); //inserted Inserted after initialization of required fields public Cycle(){ balance = deposit - 10; //subtract Subtract processing fee } public static void main(String[] args) { System.out.println("The account balance is: " + c.balance); } } |
...
Wiki Markup |
---|
This noncompliant code example uses an inner class that extends the outer class. The outer class in turn, uses the {{static}} instance of the inner class. This results in a circular initialization issue \[[Findbugs 08|AA. Java References#Findbugs 08]\]. |
...