Java靜態代碼塊、構造器、靜態主方法以及繼承后父類代碼塊的運行順序
以下代碼轉自CSDN網Flaker的Blog,鏈接:http://blog.csdn.net/flaker/archive/2009/10/10/4649367.aspx
執行結果如下:
分析:
按執行先后順序排列
1、父類的靜態代碼塊;
2、子類的靜態代碼塊;
3、靜態main方法;
4、實例化父類;
5、實例化子類。
1 public class Child extends Super{
2 static {
3 System.out.println("Child's static");
4 }
5 Child() {
6 System.out.println("Child");
7 }
8 public static void main(String[] args) {
9 System.out.println("main");
10 Child c = new Child();
11 }
12 }
13
14 public class Super {
15 static {
16 System.out.println("Super's static");
17 }
18 Super() {
19 System.out.println("Super");
20 }
21 }
2 static {
3 System.out.println("Child's static");
4 }
5 Child() {
6 System.out.println("Child");
7 }
8 public static void main(String[] args) {
9 System.out.println("main");
10 Child c = new Child();
11 }
12 }
13
14 public class Super {
15 static {
16 System.out.println("Super's static");
17 }
18 Super() {
19 System.out.println("Super");
20 }
21 }
執行結果如下:
1 Super's static
2 Child's static
3 main
4 Super
5 Child
2 Child's static
3 main
4 Super
5 Child
分析:
按執行先后順序排列
1、父類的靜態代碼塊;
2、子類的靜態代碼塊;
3、靜態main方法;
4、實例化父類;
5、實例化子類。