參考:https://blog.csdn.net/kunlyy/article/details/52176305
Java中的靜態代碼塊是在虛擬機加載類的時候,就執行的,而且只執行一次。如果static代碼塊有多個,JVM將按照它們在類中出現的先後順序依次執行它們,每個代碼塊只會被執行一次。
非靜態代碼塊是在類new一個實例的時候執行,而且是每次new對象實例都會執行。
代碼的執行順序
- 主調類的靜態代碼塊
- 對象父類的靜態代碼塊
- 對象的靜態代碼塊
- 對象父類的非靜態代碼塊
- 對象父類的構造函數
- 對象的非靜態代碼塊
- 對象的構造函數
//主調類 package test; public class StaticBlockTest1 { //主調類的非靜態代碼塊 { System.out.println("主調類的非靜態代碼塊"); } //主調類的靜態代碼塊 static { System.out.println("主調類的靜態代碼塊"); } public StaticBlockTest1(){ System.out.println("主調類的無參構造"); } public static void main(String[] args) { Children children = new Children("zhan"); children.getValue(); } } //父類 package test; public class Parent { private String name; private int age; //父類無參構造方法 public Parent(){ System.out.println("父類無參構造方法"); { System.out.println("Parent constructor method--> not static block"); } } //父類的非靜態代碼塊 { System.out.println("父類的非靜態代碼塊"); name = "zhangsan"; age = 50; } //父類靜態代碼塊 static { System.out.println("父類靜態代碼塊"); } //父類有參構造方法 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; } } //子類 package test; class Children extends Parent{ //子類靜態代碼塊 static { System.out.println("子類靜態代碼塊"); } //子類非靜態代碼塊 { System.out.println("子類非靜態代碼塊"); } //子類無參構造方法 public Children(String str){ System.out.println("子類無參構造方法"); } public void getValue(){ //this.setName("lisi"); //this.setAge(51); System.out.println(this.getName() + this.getAge()); } }
主調類的靜態代碼塊
父類靜態代碼塊
子類靜態代碼塊
父類的非靜態代碼塊
父類無參構造方法
Parent constructor method--> not static block
子類非靜態代碼塊
子類無參構造方法
zhangsan50