Wednesday, November 02, 2005
繼承關係中初始化的步驟
Father.java
public class Father {
// 1
static int f1 = 1;
// 2
int f2 = 1;
// 3
static {
System.out.println("Father static block");
}
// 4
{
System.out.println("Father non-static block");
}
// 5
Father() {
System.out.println("Father default constructor");
}
// 6
Father(int i) {
System.out.println("Father non-default constructor");
}
}
Son.java
public class Son extends Father {
// 7
static int s1 = 1;
// 8
int s2 = 1;
// 9
static {
System.out.println("Son static block");
}
// 10
{
System.out.println("Son non-static block");
}
// 11
public Son() {
System.out.println("Son default constructor");
}
// 12
public Son(int i) {
System.out.println("Son non-default constructor");
}
// 13
static void staticMethod() {
System.out.println("Son static method");
}
}
Test.java
public class Test {
public static void main(String[] args) {
// new Son();
// new Son(1);
// Son.staticMethod();
}
}
分別執行Test類別的三個statement
new Son(): 1→3→7→9→2→4→5→8→10→11- 初始Father的static成員(1, 3)
- 初始Son的static成員(7, 9)
- 初始Father的non-static成員(2, 4)
- 呼叫Father的default建構子(5)
- 初始Son的non-static成員(8, 10)
- 執行Son的建構子(11)
new Son(1): 1→3→7→9→2→4→5→8→10→12- 初始Father的static成員(1, 3)
- 初始Son的static成員(7, 9)
- 初始Father的non-static成員(2, 4)
- 呼叫Father的default建構子(5)
- 初始Son的non-static成員(8, 10)
- 執行Son的有參數建構子(12)
Son.staticMethod(): 1→3→7→9→13- 初始Father的static成員(1, 3)
- 初始Son的static成員(7, 9)
- 執行Son的static方法(13)
另外可參考TIJ 3rd.中的
- Ch4. Static data initualization
- Ch6. Initialization with inheritance



