According to the _Java Language Specification_ (JLS), [§12.4, "Initialization of Classes and Interfaces" |http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.4] \[ [JLS 2005|AA. References#JLS 05]\]: Wiki Markup
Initialization of a class consists of executing its
static
initializers and the initializers forstatic
fields (class variables) declared in the class.
Therefore, the presence of a static
field triggers the initialization of a class. However, the initializer of a static field could depend on the initialization of another class, possibly creating an initialization cycle.unmigrated-wiki-markup
The JLS also states in [§8.3.2.1, "Initializers for Class Variables" |http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.3.2.1] \[ [JLS 2005|AA. References#JLS 05]\]
At run time,
static
variables that arefinal
and that are initialized with compile-time constant values are initialized first.
...
The programmer's intent is to calculate the account balance by subtracting the processing fee from the deposited amount. However, the initialization of the c
class variable happens before the deposit
field is initialized because it appears lexically before the initialization of the deposit
field. Consequently, the value of deposit
seen by the constructor, when invoked during the static initialization of c
, is the initial value of deposit
(0) rather than the random value. As a result, the balance is always computed to be -10
.unmigrated-wiki-markup
The JLS permits implementations to ignore the possibility of such recursive initialization cycles \[ [Bloch 2005|AA. References#Bloch 05]\].
Compliant Solution (Intra-class Cycle)
...
DCL14-CPP. Avoid assumptions about the initialization order between translation units<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="c53eaf1c-3268-419b-8730-a1cc4f868137"><ac:plain-text-body><![CDATA[ | ||
[ISO/IEC TR 24772:2010http://www.aitcnet.org/isai/] | Initialization of variables [LAV] | ]]></ac:plain-text-body></ac:structured-macro> |
Bibliography
...
[ [JLS 2005AA. References#JLS 05] ] | http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.3.2.1] | ]]></ac:plain-text-body></ac:structured-macro> | |
| §12.4, Initialization of Classes and Interfaces | ||
[ [Bloch 2005AA. References#Bloch 05]] | Puzzle 49. Larger than life | ]]></ac:plain-text-body></ac:structured-macro> | <ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="06aaea64-7f88-4848-b5ef-0d4963563286"><ac:plain-text-body><![CDATA[ |
[[MITRE 2009AA. References#MITRE 09]] | [CWE-665http://cwe. mitre.org/data/definitions/665.html]. Improper initialization ]]></ac:plain-text-body></ac:structured-macro> |
...
01. Declarations and Initialization (DCL) 01. Declarations and Initialization (DCL)