定義父類 TestStatic 與子類 TestExtendStatic,均包含靜態變量、靜態塊、實例塊、構造器、普通方法與 main 方法。在子類 main 中通過向上轉型創建對象並調用被重寫的方法。
public class TestStatic {
public static String name = "china";
{ System.out.println("========父類實例塊========"); }
static { name = "England"; System.out.println("========父類靜態塊======"); }
public TestStatic() { System.out.println("========父類構造器========"); }
public static void main(String[] args) { System.out.println("========父類main========" + name); }
public void test() { System.out.println("========父類test========"); }
}
public class TestExtendStatic extends TestStatic {
{ System.out.println("========子類實例塊========"); }
static { System.out.println("========子類靜態塊======"); }
public TestExtendStatic() { System.out.println("========子類構造器========"); }
public void test() { System.out.println("========子類test========"); }
public static void main(String[] args) {
System.out.println("========子類main========" + name);
TestStatic ts = new TestExtendStatic(); // 向上轉型
ts.test();
}
}
========父類靜態塊======
========子類靜態塊======
========子類main========England
========父類實例塊========
========父類構造器========
========子類實例塊========
========子類構造器========
========子類test========
test(),實際執行子類版本在 main 中連續 new TestExtendStatic() 兩次,靜態塊僅首次執行,非靜態塊與構造器每次均執行。
若在子類 main 中執行 TestStatic ts = new TestStatic(),則不會加載子類靜態塊(除非主動引用子類),父類非靜態塊與構造器正常執行,調用 ts.test() 執行父類版本。