Wiki Markup |
---|
According to the Java Language Specification \[[JLS Section 05|AA. Java References#JLS 05]\], section 8.3.2.1, "Initializers for Class Variables|http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.3.2.1]\]: |
": |
...at run time,
static
variables that arefinal
and that are initialized with compile-time constant values are initialized first.
...
While this statement typically holds true, it can be misleading since as it does not account for instances that use values of static final
fields initialized at a later stage. Even if a field is static final
, it is not necessarily initialized at first go.
Noncompliant Code Example
This noncompliant code example contrives to calculate the account balance by subtracting the processing fee from the deposited amount, but fails miserablyto 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
.
Wiki Markup |
---|
According to the Java Language Specification \[[JLS Section05|AA. Java References#JLS 05]\], section 12.4, "Initialization of Classes and Interfaces|http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.4]\]: |
": |
Initialization of a class consists of executing its
static
initializers and the initializers forstatic
fields (class variables) declared in the class.
...
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. SinceBecause 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]\] |
...