初始化顺序 static initializer, instance initializer, constructor
The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.
Class initializers are executed in the order they are defined (top down, just like simple variable initializers) when the class is loaded (actually, when it’s resolved, but that’s a technicality).
Instance initializers are executed in the order defined when the class is instantiated, immediately before the constructor code is executed, immediately after the invocation of the super constructor.
If you remove static from int a, it becomes an instance variable which is not initialized at construction. If you also remove static from the initializer block, it then becomes an instance initializer and so int a is initialized at construction.
什么时候load 一个java class呢?
http://www.programcreek.com/2013/01/when-and-how-a-java-class-is-loaded-and-initialized/
A.class is loaded only when it is used. In summary, a class is loaded:
- when the new bytecode is executed. For example, SomeClass f = new SomeClass();
- when the bytecodes make a static reference to a class. For example, System.out.
A class is initialized when a symbol in the class is first used. When a class is loaded it is not initialized.
278

被折叠的 条评论
为什么被折叠?



