java靜態程式碼塊、靜態變數、普通程式碼塊和構造方法執行順序
阿新 • • 發佈:2021-02-16
- 靜態程式碼塊和靜態變數在使用到該類時就會初始化,要早於物件的初始化
- 靜態變數和靜態程式碼塊執行的順序取決於它們在程式碼中的順序
- 普通程式碼塊只有在建立物件時會執行,並且執行順序優先於構造方法
- 執行順序:靜態程式碼塊和靜態變數 -> 普通程式碼塊 -> 構造方法
public class Parent {
static String name = "parent";
static {
System.out.println("Parent靜態程式碼塊,name=" + name) ;
}
Parent() {
System.out.println("Parent構造方法");
}
{
System.out.println("Parent普通程式碼塊");
}
public static void main(String[] args) {
Parent parent = new Parent();
}
}
執行結果:
>>Parent靜態程式碼塊,name=parent
>>Parent普通程式碼塊
>> Parent構造方法
在上面示例中,如果變數name的定義在static{}程式碼塊下面,則編譯就會報錯,這也側面證明了靜態變數和靜態程式碼塊是根據程式碼中的位置來決定初始化順序的
子類和父類中靜態變數、靜態程式碼塊、普通程式碼塊、構造方法的執行順序:
- -> 父類靜態程式碼塊/靜態變數
- -> 子類靜態程式碼塊/靜態變數
- -> 父類普通程式碼塊
- -> 父類構造方法
- -> 子類普通程式碼塊
- -> 子類構造方法
public class Parent {
static String name = "parent";
static {
System.out.println("Parent靜態程式碼塊,name=" + name);
}
Parent() {
System.out.println("Parent構造方法");
}
{
System.out.println("Parent普通程式碼塊");
}
static class Child extends Parent{
static String name = "child";
static {
System.out.println("Child靜態程式碼塊,name=" + name);
}
Child() {
System.out.println("Child構造方法");
}
{
System.out.println("Child普通程式碼塊");
}
}
public static void main(String[] args) {
Child child = new Child();
}
}
執行結果:
>>Parent靜態程式碼塊,name=parent
>>Child靜態程式碼塊,name=child
>>Parent普通程式碼塊
>>Parent構造方法
>>Child普通程式碼塊
>>Child構造方法