Java Initialization
程式範例
public class Parent {
static int staticVariable;
int nonStaticVariable;
//類別初始化時,只會被執行一次。
static {
System.out.println("Parent static initialization block.");
staticVariable = 6;
}
//物件初始化時,每次都會被執行一次。
{
System.out.println("Parent object initialization block.");
nonStaticVariable = 6;
}
public Parent() {
System.out.println("Parent constructor.");
}
}
public class Child extends Parent {
//類別初始化時,只會被執行一次。
static {
System.out.println("Child static initialization block.");
}
//物件初始化時,每次都會被執行一次。
{
System.out.println("Child object initialization block.");
}
public Child() {
System.out.println("Child constructor.");
}
}
public class Other {
public static void main(String args[]) {
System.out.println("First test.");
System.out.println("====================================");
new Parent();
new Parent();
System.out.println();
System.out.println("Second test.");
System.out.println("====================================");
new Child();
}
}
執行結果:
First test.
====================================
Parent static initialization block.
Parent object initialization block.
Parent constructor.
Parent object initialization block.
Parent constructor.
Second test.
====================================
// Parent static initialization block. // 在First test已初始過,這裡就不執行。
Child static initialization block.
Parent object initialization block.
Parent constructor.
Child object initialization block.
Child constructor.
參考網站
https://stackoverflow.com/questions/3987428/what-is-an-initialization-block