題目:
子類A繼承父類B,A a=new A();則父類B夠着函數、父類B靜態代碼塊、父類B非靜態代碼塊執行的先後順序是?
正確的執行順序是:杜磊B靜態代碼塊-》子類A靜態代碼塊-》父類B非靜態代碼塊-》父類B構造函數-》子類A非靜態代碼塊-》子類A構造函數
也就是説非靜態初始化塊的執行順序要在構造函數之前。
1 class SuperClass{ 2 private static String str="Spuer Class Static Variable"; 3 static{ 4 System.out.println("Spuer Class Static Block:"+str); 5 } 6 public SuperClass(){ 7 System.out.println("Spuer class Constructor Menthod"); 8 } 9 { 10 System.out.println("super class Block"); 11 } 12 13 } 14 15 public class ObjectInit extends SuperClass{ 16 private static String str="Class Static Variable"; 17 static{ 18 System.out.println{"Class Static Block:"+str}; 19 } 20 public ObjectInit(){ 21 System.out.println("constructor Menthod"); 22 } 23 { 24 System.out.println("Class Block"); 25 } 26 public static void main(String[] args){ 27 @SuppressWarnings("unused") 28 ObjectInit a = new ObjectInit(); 29 } 30 } 執行完之後可以看到順序如下:
Spuer Class Static Block:Spuer Class Static Variable
Class Static Block:Spuer Class Static Variable
Spuer Class Block
Spuer class Constructor Menthod
Class Block
Constructor Menthod
时间: 2024-10-11 17:34:07