现在有一个Parent
类和一个Son
类, 代码分别如下:
public class Parent {
static {
System.out.println(" order 0");
}
private static String s = init();
{
System.out.println(" order 3");
}
public Parent() {
System.out.println(" order 4");
}
public void doSm(){
System.out.println("Class is :"+this.getClass().getName());
System.out.println("this: "+this);
}
private static String init() {
System.out.println(" order 1");
return "";
}
}
public class Son extends Parent {
static {
System.out.println("order 2");
}
{
System.out.println(" order 5");
}
public Son() {
System.out.println("order 6");
}
}
main
方法中的代码如下:
public static void main(String[] args) {
Parent p = new Son();
p.doSm();
}
则执行结果为:
order 0
order 1
order 2
order 3
order 4
order 5
order 6
Class is :Son
this: Son@5fe5c6f
Java 父子类加载顺序为:
- 首先加载
静态语句块
和静态属性
, 先父后子, 同类中的顺序执行 - 其次加载父类中的
非静态语句块
和构造方法
- 然后加载子类中的
非静态语句块
和构造方法