程序如下:
class Insect extends father {
private int i = 9;
protected int j;
Insect() {
System.out.println("i = " + i + ", j = " + j);
j = 39;
}
private static int x1 =
printInit("static Insect.x1 initialized");
static int printInit(String s) {
System.out.println(s);
return 47;
}
}
public class test extends Insect {
private int k = printInit("Beetle.k initialized");
public test() {
System.out.println("k = " + k);
System.out.println("j = " + j);
}
private static int x2 =
printInit("static Beetle.x2 initialized");
public static void main(String[] args) {
System.out.println("Beetle constructor");
// test b = new test();
}
}
output:
static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
将 // test b = new test();注释取消之后 output:
static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
i = 9, j = 0
Beetle.k initialized
k = 47
j = 39
要点 :在对better类加载过程中,编译器注意到有一个基类,于是对基类进行加载,不管是否打算产生一个该基类的对象,这都要发生。加载过程是最先执行的,static对象是在加载过程中创建的,所以先输出前两句。