子类继承父类,初始化以及方法调用顺序
// 父类
public class ParentA {
private static int i=5;
private int j;
static {
System.out.println("static A");
System.out.println("ParentA static i = "+i);
}
{ System.out.println("I'm A class");
System.out.println("ParentA static = "+j);
}
public ParentA() {
System.out.println("HelloA");
}
public void function() {
System.out.println("A function");
}
}
public class SubClassB extends ParentA {
static { System.out.println("static B"); }
{ System.out.println("I'm B class"); }
public SubClassB() {
System.out.println("HelloB");
}
public void function() {
System.out.println("B function");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new SubClassB().function();
}
}
输出结果:
static A
ParentA static i = 5
static B
I'm A class
ParentA static j = 0
HelloA
I'm B class
HelloB
B function
父类中静态成员变量和静态代码块——子类中静态成员变量和静态代码块——父类中普通成员变量和代码块——父类构造方法——子类中普通成员变量和代码块——子类构造方法