標籤:lis 虛擬機器 順序 lan static his extends main 依次
參考:http://uule.iteye.com/blog/1558891
Java中的靜態代碼塊是在虛擬機器載入類的時候,就執行的,而且只執行一次。如果static代碼塊有多個,JVM將按照它們在類中出現的先後順序依次執行它們,每個代碼塊只會被執行一次。
非靜態代碼塊是在類new一個執行個體的時候執行,而且是每次new對象執行個體都會執行。
代碼的執行順序
- 主調類的靜態代碼塊
- 對象父類的靜態代碼塊
- 對象的靜態代碼塊
- 對象父類的非靜態代碼塊
- 對象父類的建構函式
- 對象的非靜態代碼塊
- 對象的建構函式
範例程式碼
public class StaticBlockTest1 { //主調類的非靜態代碼塊 { System.out.println("StaticBlockTest1 not static block"); } //主調類的靜態代碼塊 static { System.out.println("StaticBlockTest1 static block"); } public StaticBlockTest1(){ System.out.println("constructor StaticBlockTest1"); } public static void main(String[] args) { Children children = new Children(); children.getValue(); }}class Parent{ private String name; private int age; //父類無參構造方法 public Parent(){ System.out.println("Parent constructor method"); { System.out.println("Parent constructor method--> not static block"); } } //父類的非靜態代碼塊 { System.out.println("Parent not static block"); name = "zhangsan"; age = 50; } //父類靜態代碼塊 static { System.out.println("Parent static block"); } //父類有參構造方法 public Parent(String name, int age) { System.out.println("Parent constructor method"); this.name = "lishi"; this.age = 51; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}class Children extends Parent{ //子類靜態代碼塊 static { System.out.println("Children static block"); } //子類非靜態代碼塊 { System.out.println("Children not static block"); } //子類無參構造方法 public Children(){ System.out.println("Children constructor method"); } public void getValue(){ //this.setName("lisi"); //this.setAge(51); System.out.println(this.getName() + this.getAge()); }}
輸出結果
StaticBlockTest1 static block //主調類的靜態代碼塊Parent static block //父類的靜態代碼塊Children static block //子類的靜態代碼塊Parent not static block //父類的非靜態代碼塊Parent constructor method //父類的建構函式Parent constructor method--> not static blockChildren not static block //主調類的非靜態代碼塊Children constructor method //主調類的建構函式zhangsan50 //主調main方法
總結:
- 按照前面提到的順序執行
- 子類定義無參構造方法,調用的父類也是無參構造方法
(轉) Java 靜態代碼塊和非靜態代碼塊