static 欄位static {} 靜態區塊static 欄位static {} 靜態區塊{} 實例初始化區塊{} 實例初始化區塊
package nie.test.extend;
public class Test {
public static void main(String[] args) {
new Son("s");
}
}
class Father {
static protected String s = "father_static_property_string"; // 1
protected String b = "father_normal_property_string"; // 5
static {
s = "o"; // 2
System.out.print("d");
System.out.print(s); // 輸出: do
}
{
b = "r"; // 6
System.out.print("a");
System.out.print(b); // 輸出: ar
}
Father() {
this("@"); // 7: 呼叫 Father(String)
System.out.print("1"); // 8
}
Father(String s) {
System.out.print(s); // 輸出: @
}
}
class Son extends Father {
public static String s = "son_static_property_string"; // 3
public String b = "son_normal_property_string"; // 9
static {
s = "j"; // 4
System.out.print("t");
System.out.print(s); // 輸出: tj
}
{
b = "3"; // 10
System.out.print("6");
System.out.print(b); // 輸出: 63
}
Son() {
System.out.print("."); // 11
}
Son(String s) {
this(); // 呼叫 Son()
System.out.print("com"); // 12
}
}
dotjar63.com
逐段對應:
do → 父 static 區塊tj → 子 static 區塊ar → 父實例區塊@ → 父建構子(String)1 → 父建構子()63 → 子實例區塊. → 子建構子()com → 子建構子(String)new 一次執行,父→子順序this() 先於本體執行;super() 隱含於子建構子首行static 欄位/區塊 不參與實例化順序,僅在類載入階段若您的輸出與 dotjar63.com 完全一致,恭喜掌握 Java 初始化機制!