/**
* 实例化先后顺序:父类的静态变量、子类的静态变量、父类的非静态变量、父类的构造器、子类的非静态变量、子类的构造器
*
* @author zhang
*
*/
public class Father {
public static void main(String[] args) {
System.out.println("Son constructor");
Father f = new Son();
f.f();// 如果子类重写父类的方法,会调用子类的
f.g();// 如果子类没有该方法,则调用父类的
((Son) f).h();// 子类有父类没有时,需要强转成子类的类型才可调用
}
private int i = 9;
protected int j;
public Father() {
System.out.println("i=" + i + ",j=" + j);
j = 39;
}
int a = print("if before father constructor");
int b = print("after father constructor");
private static int x1 = print("static Father.x1 initialized");
public static int print(String s) {
System.out.println(s);
return 47;
}
public void f() {
System.out.println("Father.f()");
}
public void g() {
System.out.println("Father.g()");
}
}
class Son extends Father {
public Son() {
System.out.println("k=" + k);
System.out.println("j=" + j);
}
public int k = print("Son.k initialized");
private static int x2 = print("static Son.x2 initialized");
@Override
public void f() {
System.out.println("Son.f()");
}
public void h() {
System.out.println("Son.h()");
}
}
控制打印:
static Father.x1 initialized
Son constructor
static Son.x2 initialized
if before father constructor
after father constructor
i=9,j=0
Son.k initialized
k=47
j=39
Son.f()
Father.g()
Son.h()