- package initialSeq;
- public class Parent
- {
- private static int i = 10;
- static
- {
- System.out.println(i);
- System.out.println("Init parent static block");
- }
- {
- System.out.println("Init parent program block");
- }
-
- public Parent()
- {
- System.out.println("Init parent structure");
- }
- public int method()
- {
- return ++i;
- }
- }
- package initialSeq;
- public class Child extends Parent
- {
- private static String str = "Hello";
- static
- {
- System.out.println(str);
- System.out.println("Init child static block");
- }
- {
- System.out.println("Init child program block");
- }
-
- public Child()
- {
- System.out.println("Init child structure");
- }
-
- public static void main(String args[])
- {
- Child c = new Child();
- System.out.println(c.method());
- System.out.println("-----I am a cut-off line----");
- Child c1 = new Child();
- System.out.println(c1.method());
- }
- }
输出结果:
10 Init parent static block Hello Init child static block Init parent program block Init parent structure Init child program block Init child structure 11 -----I am a cut-off line---- Init parent program block Init parent structure Init child program block Init child structure 12
初始化顺序:父类静态变量->父类静态快->子类静态变量->子类静态块->父类程序块->父类构造函数->子类程序块->子类构造函数。
当我们new子类对象的时候会想加载父类和子类,这时父类和子类静态变量及静态块被初始化,后面接着的顺序父类程序块,父类构造函数子类程序块, 子类够着函数,相信大家应该都好理。由于第二次再new子类对象的时候,父类和子类已经被加载过了,所以就不会重复加载,即不会重复初始化静态变量及静态 块,所以在第二次new Child的时候没有静态块的内容输出,并且父类的i的值没有被初始化为10。