class Base{
Insect() {
System.out.println("Insect Constructor");
}
private static int x1 =
printInit("static Base.x1 initialized!");
static int printInit(String s) {
System.out.println(s);
return 50;
}
}
public class Child extends Base{
private int k = printInit("static Child.k initialized!");
public Beetle() {
System.out.println("k = " + k);
}
private static int x2 =
printInit("static Child.x2 initialized!");
public static void main(String[] args) {
System.out.println("Child constructor");
Child c = new Child();
}
}
首先试图访问main方法,发现有基类,自动加载基类,所以:
加载类的时候会自动向上加载基类,无论是否实例化了这个子类,所以main方法中父类的static一定会执行.而实例化的时候,是先执行父类的构造器.