package staticinit.one;public class Main1 { public static void main(String[] args) { System.out.println("第一遍初始化StaticOrInstance..."); new StaticOrInstance(); System.out.println("第二遍初始化StaticOrInstance..."); new StaticOrInstance(); /* * 输出结果: * 第一遍初始化StaticOrInstance... * Mug(3) * Mug(4) * Mug(1) * Mug(2) * StaticOrInstance constructor... * 第二遍初始化StaticOrInstance... * Mug(1) * Mug(2) * StaticOrInstance constructor... */ }}class StaticOrInstance { public Mug mug1; public Mug mug2; public static Mug mug3; public static Mug mug4; { mug1 = new Mug(1); mug2 = new Mug(2); } static { mug3 = new Mug(3); mug4 = new Mug(4); } public StaticOrInstance() { System.out.println("StaticOrInstance constructor..."); }}class Mug { public Mug() { } public Mug(int i) { System.out.println("Mug(" + i + ")"); }}
注:1.在类初始化时,先初始化静态块或变量,再初始化非静态块或变量(StaticOrInstance类中静态块位于非静态块后面,但是输出结果中静态块先初始化);2.静态块或变量只会在第一次初始化时初始化,而非静态块或变量会在每一次类初始化时执行初始化(在第二次初始化时静态块没有再次初始化);3.静态块(变量)和非静态块(变量)均在构造方法之前被初始化。