Java對象創建階段的代碼調用順序


在創建階段系統通過下面的幾個步驟來完成對象的創建過程

  • 為對象分配存儲空間
  • 開始構造對象
  • 從超類到子類對static成員進行初始化
  • 超類成員變量按順序初始化,遞歸調用超類的構造方法
  • 子類成員變量按順序初始化,子類構造方法調用

本文重點演示第三步到第五步:

Grandpa類

 1 package com.xinye.test;
 2 
 3 public class Grandpa {
 4     {
 5         System.out.println("執行Grandpa的普通塊");
 6     }
 7     static {
 8         System.out.println("執行Grandpa的靜態快");
 9     }
10     public Grandpa(){
11         System.out.println("執行Parent的構造方法");
12     }
13     static{
14         System.out.println("執行Grandpa的靜態快222222");
15     }
16     {
17         System.out.println("執行Grandpa的普通快222222");
18     }
19 }

Parent類

 1 package com.xinye.test;
 2 
 3 public class Parent extends Grandpa{
 4     protected int a = 111;
 5     {
 6         System.out.println("執行Parent的普通塊");
 7     }
 8     static {
 9         System.out.println("執行Parent的靜態快");
10     }
11     public Parent(){
12         System.out.println("執行Parent的構造方法");
13     }
14     public Parent(int a){
15         this.a = a ;
16         System.out.println("執行Parent的構造方法:InitParent(int a)");
17     }
18     static{
19         System.out.println("執行Parent的靜態快222222");
20     }
21     {
22         System.out.println("執行Parent的普通快222222");
23     }
24 }

Child類

 1 package com.xinye.test;
 2 
 3 public class Child extends Parent {
 4     {
 5         System.out.println("執行Child的普通塊");
 6     }
 7     static {
 8         System.out.println("執行Child的靜態快");
 9     }
10     public Child(){
11         super(222);
12         System.out.println("a = " + a);
13         System.out.println("執行Child的構造方法");
14     }
15     static{
16         System.out.println("執行Child的靜態快222222");
17     }
18     {
19         System.out.println("執行Child的普通快222222");
20     }
21 }

測試類

 1 package com.xinye.test;
 2 
 3 public class Test {
 4 
 5     public static void main(String[] args) {
 6         /**
 7          * 
 8          *  第一步:
 9          *      Grandpa如果有靜態塊,按照Grandpa的靜態塊聲明順序依次執行
10          *      Parent中如果有靜態塊,按照Parent中的靜態塊聲明順序依次執行
11          *      Child中如果有靜態塊,按照Child中的靜態塊聲明順序依次執行
12          *  第二部:
13          *      如果Grandpa中有普通塊,按照Grandpa的普通塊聲明順序依次執行
14          *          執行完畢后,執行被調用的構造方法(如果Parent調用了Grandpa中的特定構造;如果沒有則調用默認構造)
15          *      如果Parent中有普通塊,按照Parent的普通塊的聲明順序依次執行
16          *          執行完畢后,執行被調用的構造方法(如果Child調用了Parent的特定構造;如果沒有則調用默認構造)
17          *         如果Child中有普通塊,按照Child的普通塊的聲明順序依次執行
18          *             執行完畢后,執行被客戶端調用的特定構造方法
19          */
20         
21         new Child();
22     }
23 }

執行結果

 1 執行Grandpa的靜態快
 2 執行Grandpa的靜態快222222
 3 執行Parent的靜態快
 4 執行Parent的靜態快222222
 5 執行Child的靜態快
 6 執行Child的靜態快222222
 7 執行Grandpa的普通塊
 8 執行Grandpa的普通快222222
 9 執行Parent的構造方法
10 執行Parent的普通塊
11 執行Parent的普通快222222
12 執行Parent的構造方法:InitParent(int a)
13 執行Child的普通塊
14 執行Child的普通快222222
15 a = 222
16 執行Child的構造方法

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM