class Cup{ Cup(int marker){ System.out.println("Cup("+marker+")"); } void f1(int marker){ System.out.println("f1("+marker+")"); } } class Cups{ static Cup cup1 = new Cup(1); Cup cup2 = new Cup(2); { Cup cup3 = new Cup(3); } static{ Cup cup4 = new Cup(4); } Cups(){ System.out.println("Cups()"); } static void f2(int marker){ System.out.println("f2("+marker+")"); } } public class ExplicitStatic { public static void main(String[] args) { System.out.println("Inside main()"); Cups.f2(5); // Cups cups = new Cups(); } }
輸出結果為:
Inside main() Cup(1) Cup(4) f2(5) Process finished with exit code 0
此結果驗證了1-2中的規律6:呼叫除建構函式外靜態方法只會引發靜態初始化,而不會引發普通初始化。因為類中的普通成員變數cup2、cup3並未被顯示初始化。
public class ExplicitStatic { public static void main(String[] args) { System.out.println("Inside main()"); // Cups.f2(5); Cups cups = new Cups(); } }
輸出的結果為:
Inside main() Cup(1) Cup(4) Cup(2) Cup(3) Cups() Process finished with exit code 0
此結果驗證了1-2中的規律4、5 以及 初始化順序的優先順序。