package Study.Initialization;class Base{private String str1=init("str1");private String str2=init("str2");public static String str3=init("static str3");public Base(String str1,String str2){System.out.println("Run Construction Base");this.str1=str1;this.str2=str2;}protected static String init(String str){System.out.println(str);return str+" init";}}class Derived extends Base{ private String str4=init("str4"); public static String str5=init("static str5"); public Derived(String str1,String str2,String str4){ super(str1,str2); System.out.println("Run Construction Derived"); this.str4=str4; }}public class extendInitialization {public static void main(String[] args) {System.out.println("run extendInitialization.main()");Derived d=new Derived("construction str1","construction str2","construction str4"); System.out.println("----------------------------------------");Derived d2=new Derived("construction str11","construction str22","construction str44"); }}
運行結果:
run extendInitialization.main()
static str3
static str5
str1
str2
Run Construction Base
str4
Run Construction Derived
----------------------------------------
str1
str2
Run Construction Base
str4
Run Construction Derived
總結:
Derived的初始化順序:
1.按定義時的順序初始化基類的static成員
2..按定義時的順序初始化擴充類的static成員
(以上兩條是對第一次定義擴充類對象時運行)
3.按定義時順序執行基類的指定初始化
4.執行基類的建構函式
5 按定義時的順序執行擴充類的指定初始化
6.行擴充類的建構函式