在Java類被new的過程當中,執行順序以下:函數
在實現繼承的類被new的過程當中,初始化執行順序以下:測試
1. 靜態代碼塊:code
static {
} 繼承
2. 非靜態代碼塊it
{
} class
靜態代碼塊和非靜態代碼塊的異同點以下:test
public
class
InitOderTest {
變量
public
static
String STATIC_FIELD =
"靜態屬性"
;
構造函數
// 靜態塊
static
static
{
System.out.println(STATIC_FIELD);
System.out.println(
"靜態代碼塊"
);
}
public
String field =
"非靜態屬性"
;
// 非靜態塊
{
System.out.println(field);
System.out.println(
"非靜態代碼塊"
);
}
public
InitOderTest() {
System.out.println(
"無參構造函數"
);
}
public
static
void
main(String[] args) {
InitOderTest test =
new
InitOderTest();
}
}
執行結果:
public class ParentTest {
public static String PARENT_STATIC_FIELD = "父類-靜態屬性";
// 父類-靜態塊
static {
System.out.println(PARENT_STATIC_FIELD);
System.out.println("父類-靜態代碼塊");
}
public String parentField = "父類-非靜態屬性";
// 父類-非靜態塊
{
System.out.println(parentField);
System.out.println("父類-非靜態代碼塊");
}
public ParentTest() {
System.out.println("父類—無參構造函數");
}
}
public class InitOderTest extends ParentTest{
public static String STATIC_FIELD = "靜態屬性";
// 靜態塊
static {
System.out.println(STATIC_FIELD);
System.out.println("靜態代碼塊");
}
public String field = "非靜態屬性";
// 非靜態塊
{
System.out.println(field);
System.out.println("非靜態代碼塊");
}
public InitOderTest() {
System.out.println("無參構造函數");
}
public static void main(String[] args) {
new InitOderTest();
new InitOderTest();
}
}
執行結果以下: