Wiki Markup |
---|
According to \[[JLS 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 are final and that are initialized with compile-time constant values are initialized first."
...
Wiki Markup |
---|
According to \[[JLS 05|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 for static 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. Since such recursive attempts are ignored by the JVM, the default value of {{deposit}} is {{0}} during the initialization |
. Puzzlers. \[[Bloch 05|AA. Java References#Bloch 05]\] |
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 |
---|
\[[JLS 05|AA. Java References#JLS 05]\] Sections [8.3.2.1, Initializers for Class Variables|http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.3.2.1]; [12.4, Initialization of Classes and Interfaces|http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.4]
\[[Bloch 05|AA. Java References#Bloch 05]\] Puzzle 49: Larger Than Life |
...