今天遇到一個問題就是一個類的靜態屬性,靜態塊,構造塊以及構造方法的執行順序是怎樣的,於是寫一個demo測試一下。
定義一個Person類
public class Person {
private static User mUser = new User("Person");
static {
System.out.println("Person靜態塊");
}
{
System.out.println("Person構造塊");
}
public Person() {
System.out.println("Person()");
}
public static void main(String[] args) throws Exception {
new Person();
}
}
這裏定義一個Person類,他有一個靜態屬性User 之所以這樣做是爲了打印靜態屬性的執行順序,還有靜態塊,構造塊,以及默認的構造方法,以及一個main函數。很簡單,下面給出User類的代碼
public class User {
public User(String come) {
System.out.println(come + "User()");
}
}
下面我們看看運行main函數執行結果如下:
發現執行的順序是:
靜態屬性 –> 靜態塊 –> 構造塊 –> 構造方法
下面我們再來看看,如果Person有一個子類,那麼執行結果會怎樣。
定義一個Student 繼承至 Person()
public class Student extends Person {
private static User mUser = new User("Student");
static {
System.out.println("Student靜態塊");
}
{
System.out.println("Student構造塊");
}
public Student() {
System.out.println("Student()");
}
}
在 Person的main 方法運行:
new Student();
結果如下:
結果表明:
先執行 父類的靜態屬性–>父類的靜態塊–>子類的靜態屬性–>子類的靜態塊–>父類的構造塊–>父類的構造方法–>子類的構造塊–>子類的構造方法