1.測試類
public class Demo extends SuperDemo { //靜態代碼塊 static{ System.out.println("this is static block"); } //普通代碼塊 { System.out.println("this is normal block"); } //默認構造函數 public Demo(){ System.out.println("this is demo constructor"); } public static void main(String[] args) { Demo d = new Demo(); } }
2.測試類的父類
public class SuperDemo { //靜態代碼塊 static{ System.out.println("this is super static block"); } //普通的代碼塊 { System.out.println("this is super normal block"); } //默認構造函數 public SuperDemo(){ System.out.println("this is SuperDemo constructor"); } }
3.輸出結果
this is super static block
this is static block
this super is normal block
this is SuperDemo constructor
this is normal block
this is demo constructor
由此我們得到,java中靜態代碼塊首先被執行,且只被執行一次,當實例化一個對象之后,將會首先執行非靜態代碼塊,接着執行構造函數。
當一個類從被JVM裝載開始,各種代碼的執行順序大致如下:
被JVM裝載->執行父類的相關代碼->如果有靜態初始化,先執行靜態初始化,且只執行一次,以后即使有該類實例化,也不會再執行->如果有靜態代碼塊,以與靜態初始化一樣的方式執行->如果有new語句帶來的實例化,先為成員變量分配空間,並綁定參數列表,隱式或顯式執行super(),即父類的構造方法,->執行非靜態代碼塊-〉執行本類的構造函數-〉執行其他代碼