子類:
public class TestPriority extends TestFatherPriority {
public TestPriority() {
System.out.println("子類構造方法");
}
static {
System.out.println("子類靜態代碼塊");
}
{
System.out.println("子類代碼塊");
}
public static void main(String[] args) {
System.out.println("before子類main");
new TestPriority();
System.out.println("after子類main");
}
}
父類:
public class TestFatherPriority {
public TestFatherPriority() {
System.out.println("父類構造方法");
}
static {
System.out.println("父類靜態代碼塊");
}
{
System.out.println("父類代碼塊");
}
public static void main(String[] args) {
System.out.println("before父類main");
new TestFatherPriority();
System.out.println("after父類main");
}
}
運行子類main方法,輸出:
父類靜態代碼塊
子類靜態代碼塊
before子類main
父類代碼塊
父類構造方法
子類代碼塊
子類構造方法
after子類main
得出結論:
①無繼承的情況下執行順序:
靜態代碼塊->main方法->代碼塊->構造方法
②有繼承的情況下執行順序:
父類靜態代碼塊->子類靜態代碼塊->main方法->父類代碼塊->父類構造方法->子類代碼塊->子類構造方法