该代码从Thinking in java第四版中拷贝,很好的反应了java中含有static成员与方法的继承初始化顺序,推荐阅读Thinking in java的原文。
代码如下:
class Insect { private int i = 9; protected int j; Insect(){ System.out.println("i = " + i + ", j = " + j); j = 49; } private static int x1 = printInit("static Insect.x1 initialized"); static int printInit(String s) { System.out.println(s); return 47; } } public class Beetle extends Insect{ private int k = printInit("Beetle.k initialized"); public Beetle() { 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"); Beetle b = new Beetle(); } }
得到的结果如下:
static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
i = 9, j = 0
Beetle.k initialized
k = 47
j = 49
可以看出,在main方法new出对象之前,先创建了基类的静态成员,然后创建了子类的静态成员,(这里静态成员的赋值用到了静态函数),然后在main函数中new出对象的过程中,先调用了基类的构造方法,然后调用子类的构造方法。