java中的静态代码块等执行顺序

时间:2022-01-05 09:17:02

http://www.cnblogs.com/naruto469/p/3608459.html

public class Print {
2
3 public Print(String s){
4 System.out.print(s + " ");
5 }
6 }
 1 public class Test1 {
2
3 public static Print obj1 = new Print("1");
4
5 public Print obj2 = new Print("2");
6
7 public static Print obj3 = new Print("3");
8
9 static{
10 new Print("4");
11 }
12
13 public static Print obj4 = new Print("5");
14
15 public Print obj5 = new Print("6");
16
17 public Test1(){
18 new Print("7");
19 }
20
21 }
 1 public class Test2 extends Test1{
2
3 static{
4 new Print("a");
5 }
6
7 public static Print obj1 = new Print("b");
8
9 public Print obj2 = new Print("c");
10
11 public Test2(){
12 new Print("d");
13 }
14
15 public static Print obj3 = new Print("e");
16
17 public Print obj4 = new Print("f");
18
19 public static void main(String [] args){
20 Test1 obj1 = new Test2();
21 Test1 obj2 = new Test2();
22 }
23 }

执行main方法,程序输出顺序为: 1 3 4 5 a b e 2 6 7 c f d 2 6 7 c f d 
输出结果表明,程序的执行顺序为: 
如果类还没有被加载: 
1、先执行父类的静态代码块和静态变量初始化,并且静态代码块和静态变量的执行顺序只跟代码中出现的顺序有关。 
2、执行子类的静态代码块和静态变量初始化。 
3、执行父类的实例变量初始化 
4、执行父类的构造函数 
5、执行子类的实例变量初始化 
6、执行子类的构造函数 
如果类已经被加载: 
则静态代码块和静态变量就不用重复执行,再创建类对象时,只执行与实例相关的变量初始化和构造方法。