简单代码:
package example;
class Parent {
static String name = "hello";
{
System.out.println("3 parent block");
}
static {
System.out.println("1 parent static block");
}
public Parent() {
System.out.println("4 parent constructor");
}
}
class Child extends Parent {
static String childName = "hello";
{
System.out.println("5 child block");
}
static {
System.out.println("2 child static block");
}
public Child() {
System.out.println("6 child constructor");
}
}
package example;
public class StaticIniBlockOrderTest {
public static void main(String[] args) {
new Child();
}
}
输出结果:
1 parent static block
2 child static block
3 parent block
4 parent constructor
5 child block
6 child constructor
执行顺序总结:
1、执行父类静态代码块,执行子类静态代码块
2、执行父类非静态代码块,执行父类构造函数,执行子类非静态代码块,执行子类构造函数