public class Paramter {
static {
System.out.println("Paramter static");
}
public Paramter(String s){
System.out.println("Paramter constructor " + s);
}
}
public class Parent {
private static Paramter staticParamter = new Paramter("Parent static");
private Paramter paramter = new Paramter("Parent");
static {
System.out.println("Parent static");
}
public Parent(){
System.out.println("Parent constructor");
}
}
public class Children extends Parent{
private static Paramter staticParamter = new Paramter("Children static");
private Paramter paramter = new Paramter("Children");
static {
System.out.println("children static");
}
public Children(){
System.out.println("children constructor");
}
public static void main(String[] args) {
Children children1 = new Children();
Children children2 = new Children();
}
}
Paramter static
Paramter constructor Parent static
Parent static
Paramter constructor Children static
children static
Paramter constructor Parent
Parent constructor
Paramter constructor Children
children constructor
Paramter constructor Parent
Parent constructor
Paramter constructor Children
children constructor
结论
- 先加载静态成员变量的类,实例化静态成员变量,再执行静态代码块,实例化非静态成员变量,最后执行构造方法
- 如果有父类实例化父类的静态成员变量,静态代码块,再执行实例化子类的静态成员变量,子类的静态代码块,接着实例化父类非静态成员变量,然后是父类的构造方法,最后实例化子类非静态成员变量,然后子类的构造方法
- 静态代码块和静态成员变量只在类加载期间执行一次,后续实例化只运行非静态成员变量以及构造方法