JAVA 父类与子类初始化顺序问题
main方法-->子类对象的初始化语句(new className()语句)--->子类构造【因为继承的缘故,它先不会执行】--->父类构造【这一步先不会执行】--->父类静态变量----->子类静态变量---->初始化父类变量(按顺序)--->父类构造---->子类变量初始初始(按顺序)--->子类构造--->运行main后的语句--->程序结束。(按eclipse得debug顺序记录)
无继承的类初始化顺序:静态变量--->静态初始化块------>变量---->初始化块----->构造器。
附测试程序:
class Insect { private int i =9; protected int j; public Insect() { System.out.println("i = "+i+",j="+j); j=39; } private static int x1 = printInit("static intx1 initialized"); static int printInit(String s) { System.out.println(s); return 47; } }
public class Beetle extends Insect { private int k = printInit("beetle.k initialized"); 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 intx1 initialized static beetle.x2 initialized beetle constructor i = 9,j=0 beetle.k initialized k=47 j = 39
posted on 2013-11-06 00:59 heartstage 阅读(1139) 评论(0) 编辑 收藏 举报