public class House {
public House(String name){
System.out.println(name+" 's house");
}
}
public class GrandFather{
protected GrandFather(){
System.out.println("GrandFather()");
}
static{
System.out.println("static block in GrandFather");
}
{
System.out.println("initialization in GrandFather");
}
static House h1 = new House("static GrandFather");
House h2 = new House("GrandFather");
}
public class Father extends GrandFather{
static {
System.out.println("static block in Father");
}
static House h1 = new House("static Father");
protected Father(){
System.out.println("Father()");
}
{
System.out.println("initialization in Father");
}
}
public class son extends Father{
son() {
System.out.println("son()");
}
public static void main(String[] args) {
System.out.println("********entry in main********");
new son();
}
static House h1 = new House("static son");
static{
System.out.println("static block in son");
}
House h2 = new House("son");
{
System.out.println("block in son");
}
}
運(yùn)行結(jié)果:
static block in GrandFather
static GrandFather 's house
static block in Father
static Father 's house
static son 's house
static block in son
********entry in main********
initialization in GrandFather
GrandFather 's house
GrandFather()
initialization in Father
Father()
son 's house
block in son
son()
結(jié)論:
在繼承關(guān)系中,類成員的初始化遵照以下順序
①最外層超類的靜態(tài)成員
②超類靜態(tài)成員
③子類靜態(tài)成員
④最外層超類的非靜態(tài)成員
⑤最外層超類的構(gòu)造器
⑥超類的非靜態(tài)成員
⑦超類的構(gòu)造器
⑧子類的非靜態(tài)成員
⑨子類構(gòu)造器
其中,相同類型(同為靜態(tài)或者非靜態(tài)成員)復(fù)數(shù)成員的初始化,遵照其在代碼中出現(xiàn)的順序。
聯(lián)系客服