考虑类中有static变量的时候,测试程序如下:
FatherProp.java:
public FatherProp( ) {
System.out.println( "I am father prop" );
}
public FatherProp( String name ) {
System.out.println( "I am father prop: " + name );
}
}
Father.java:
public class Father {
private FatherProp fatherProp = new FatherProp( "usual member" );
private static FatherProp staticfatherProp = new FatherProp( "static member" );
public Father( ) {
System.out.println( "I am father" );
}
}
SonProp.java:
public class SonProp {
public SonProp( ) {
System.out.println( "I am son prop" );
}
public SonProp( String name ) {
System.out.println( "I am son prop: " + name );
}
}
Son.java:
public class Son extends Father {
private SonProp fatherProp = new SonProp( "usual member" );
private static SonProp staticfatherprop = new SonProp( "static member" );
public Son( ) {
super( );
System.out.println( "I am son" );
}
}
Main.java:
public class Main {
public static void main( String[] args ) {
System.out.println( "test begin" );
Son son = new Son( );
}
}
输出结果如下:
test begin
I am father prop: static member
I am son prop: static member
I am father prop: usual member
I am father
I am son prop: usual member
I am son
因此,调用顺序为:
(1)初始化对象的存储空间为零或null值;
(2)按顺序调用父类中静态变量的初始化表达式;
(3)按顺序调用子类中静态变量的初始化表达式;
(5)调用父类构造函数;(如果使用super()方法指定具体的某个父类构造函数则使用指定的那个父类构造函数)
(6)按顺序分别调用子类成员变量和实例成员变量的初始化表达式;
(7)调用子类本身构造函数。