在建立階段系統經過下面的幾個步驟來完成對象的建立過程測試
本文重點演示第三步到第五步:this
Grandpa類spa
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類code
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 }
測試類blog
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的構造方法