类文件:Print.java
package net.mindview.util;
import java.io.*;
public class Print {
// Print with a newline:
public static void print(Object obj) {
System.out.println(obj);
}
}
类文件:Beetle.java
import static net.mindview.util.Print.*;
class InsectInit {
private int k = printInit("InsectInit.k initialized");
private int i = 10;
protected int j;
InsectInit() {
print("i = " + i + ", j = " + j);
j = 40;
}
private static int x3 = printInit("static Insect.x3 initialized");
static int printInit(String s) {
print(s);
return 48;
}
}
class Insect extends InsectInit {
private int k = printInit("Insect.k initialized");
private int i = 9;
protected int j;
Insect() {
print("i = " + i + ", j = " + j);
j = 39;
}
private static int x1 = printInit("static Insect.x1 initialized");
static int printInit(String s) {
print(s);
return 47;
}
}
public class Beetle extends Insect {
private int k = printInit("Beetle.k initialized");
public Beetle() {
print("k = " + k);
print("j = " + j);
}
private static int x2 = printInit("static Beetle.x2 initialized");
public static void main(String[] args) {
print("Beetle constructor");
Beetle b = new Beetle();
}
}
/*Output:
static Insect.x3 initialized
static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
InsectInit.k initialized
i = 10, j = 0
Insect.k initialized
i = 9, j = 0
Beetle.k initialized
k = 47
j = 39
*/
从输入中可以看出初始化顺序是:
顶层基类static属性--->第二层基类static属性--->导出类static属性--->main方法--->顶层基类属性--->顶层基类构造方法--->第二层基类属性--->第二层基类构造方法--->子类属性--->子类构造方法