在继承的时候,java初始化时加载的顺序是先加载完各个类的所有的静态函数,静态变量(这两个平等关系,那个在前初始化那个先);剩下的在每个类中依次进行:无名函数<==>变量(这两个平等关系,那个在前初始化那个先)-------->构造函数。静态的函数和变量是跨类执行的,不是静态的就先执行完基类再依次到下一个类。
例子如下:
package test;
class Apple{
public Apple(String str){
System.out.println("Apple("+str+")");
if("静态Son after".equals(str)){System.out.println("--------------------------静态方法全部初始化完毕");}
}
}
class GrandFather{
static Apple apple2 = new Apple("静态GrandFather before");
Apple apple = new Apple("GrandFather before");
{ System.out.println("GrandFather无名函数before");}
static{
System.out.println("GrandFather静态before");
};
public GrandFather(){
System.out.println("GrandFather构造函数 ");
System.out.println("--------------------------GrandFather初始化完毕");
};
static{
System.out.println("GrandFather静态after");
}
{ System.out.println("GrandFather无名函数after");}
Apple apple1 = new Apple("GrandFather after");
static Apple apple3 = new Apple("静态GrandFather after");
}
class Father extends GrandFather{
static Apple apple2 = new Apple("静态Father before");
Apple apple = new Apple("Father before");
{ System.out.println("Father无名函数before");}
static{
System.out.println("Father静态before");
};
public Father(){
System.out.println("Father构造函数 ");
System.out.println("--------------------------Father初始化完毕");
};
static{
System.out.println("Father静态after");
}
{ System.out.println("Father无名函数after");}
Apple apple1 = new Apple("Father before");
static Apple apple3 = new Apple("静态Father after");
}
public class Son extends Father{
static Apple apple2 = new Apple("静态Son before");
Apple apple = new Apple("Son before");
{ System.out.println("Son无名函数before");}
static{
System.out.println("Son静态函数before");
}
public Son(){
System.out.println("Son构造函数");
System.out.println("--------------------------Son初始化完毕");
};
static{
System.out.println("Son静态函数after");
}
{ System.out.println("Son无名函数after");}
Apple apple1 = new Apple("Son before");
static Apple apple3 = new Apple("静态Son after");
public static void main(String[] args){
new Son();
}
}
//output
Apple(静态GrandFather before)
GrandFather静态before
GrandFather静态after
Apple(静态GrandFather after)
Apple(静态Father before)
Father静态before
Father静态after
Apple(静态Father after)
Apple(静态Son before)
Son静态函数before
Son静态函数after
Apple(静态Son after)
--------------------------静态方法全部初始化完毕
Apple(GrandFather before)
GrandFather无名函数before
GrandFather无名函数after
Apple(GrandFather after)
GrandFather构造函数
--------------------------GrandFather初始化完毕
Apple(Father before)
Father无名函数before
Father无名函数after
Apple(Father before)
Father构造函数
--------------------------Father初始化完毕
Apple(Son before)
Son无名函数before
Son无名函数after
Apple(Son before)
Son构造函数
--------------------------Son初始化完毕