類A的定義 java
package com.sequence.test; public class A { // 靜態變量 static String name; // 靜態自由塊 static{ name = "a"; System.out.println("static filed of A inited."); } // 實例變量 String type; // 非靜態自由塊 { type = "a.type"; System.out.println("no-static filed of A inited."); } String size; // 構造函數 public A(){ size = "a.size"; System.out.println("construct func of A inited."); } }
package com.sequence.test; public class B extends A{ // 靜態自由塊 static { System.out.println("static filed of B inited."); } // 非靜態自由塊 { System.out.println("no-static filed of B inited."); } public B(){ System.out.println("constuct func of B inited."); } }
package com.sequence.test; public class InitSequenceTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub new B(); } }
輸出: 函數
1,靜態自由塊在class加載的時候執行。只會執行一次。 測試
2,非靜態自由塊在新建類的實例的時候執行。能夠屢次執行。在新建其或子類的實例時,就會執行。 spa
當存在多個同一種類型的自由塊時,執行的順序是根據他們在代碼塊中出現的順序。 code
3,當子類繼承父類,執行的順序以下:父類的靜態變量和靜態域->子類的靜態變量和靜態域->父類的非靜態自由塊->父類的構造函數->子類的非靜態自由塊->子類的構造函數 繼承