標籤:
JAVA執行順序如下:
1.首先載入所有類中調到的class。
2.先載入父類,再載入子類。
3.載入過程中,會執行靜態代碼塊。
4.new Constructor()的時候會先執行 代碼塊{},再執行 Constuctor();
5.靜態變數在載入過程中賦值,與靜態代碼塊是從上到下的執行順序。
所以輸出結果為:
1.父類靜態代碼塊。
2.子類靜態代碼塊。
3.父類 代碼塊。
4.父類建構函式。
5.子類代碼塊。
6.子類建構函式。
1 package test_static; 2 3 public class Fathor { 4 public String name="fathor"; 5 public static String sex="man"; 6 7 { 8 System.out.println("this is fathor‘s 代碼塊!"); 9 }10 11 static{12 sex="male";13 System.out.println("this is fathor‘s 靜態代碼塊!");14 }15 16 public Fathor() {17 System.out.println("Fathor‘sex is :"+sex);18 System.out.println("this is Fathor‘s Constructor");19 }20 }
1 package test_static; 2 3 public class Son extends Fathor{ 4 public String name = "son"; 5 6 public static String sex="man"; 7 8 { 9 System.out.println("this is son‘s 代碼塊!");10 }11 12 static{13 sex="male";14 System.out.println("this is son‘s 靜態代碼塊!");15 }16 17 public Son() {18 System.out.println("this is son‘s Constructor");19 System.out.println("son sex is "+sex);20 }21 }
1 package test_static;2 3 public class Test {4 public static void main(String[] args) {5 Son s = new Son();6 }7 }
執行結果:
1 this is fathor‘s 靜態代碼塊!2 this is son‘s 靜態代碼塊!3 this is fathor‘s 代碼塊!4 Fathor‘sex is :male5 this is Fathor‘s Constructor6 this is son‘s 代碼塊!7 this is son‘s Constructor8 son sex is male
Java 執行順序