舉例子:
package test_instance; public class TestClassLoaderTime { public TestClassLoaderTime(){ System.out.println("構造器執行"); } { System.out.println("靜態代碼塊執行"); } static Demo2 demo2 = new Demo2(); private Demo3 demo3 = new Demo3(); public static void main(String[] args) { System.out.println("main方法執行"); new TestClassLoaderTime(); System.out.println("TestClassLoaderTime實例化過"); } }
執行結果:
Initialization the Demo2.....
main方法執行
靜態代碼塊執行
Initializaiton the Demo3....
構造器執行
TestClassLoaderTime實例化過
所以是按照如下順序執行的:
1.Demo2的構造函數執行 (靜態屬性)
2.main方法執行
3.靜態代碼塊執行
4.Demo3的構造函數執行 (非靜態屬性)
5.構造器執行
6.TestClassLoaderTime實例化過