静态代码块、静态变量等执行顺序

 1 public class BasicTest {
 2     public static void main(String[] args) {
 3         System.out.println("m1:");
 4         Mimi m1=new Mimi();
 5         System.out.println("m2:");
 6         Mimi m2=new Mimi();
 7     }
 8 }
 9 
10 class Mimi {
11     public static int si=0; 
12     int di=si;
13     static{
14         //首先执行
15         si++;
16         System.out.println("static block1: si="+si);
17     }
18     
19     {
20         //si*=2;
21         System.out.println("block2: si="+si+", di="+di);
22     }
23     
24     static{
25         //首先执行
26         si++;
27         System.out.println("static block2: si="+si);
28     }
29 
30     public Mimi() {
31         di=10;
32         System.out.println("constructor: si="+si+", di="+di);
33         si=500;
34     }
35 }

执行顺序是:

静态成员变量初始化

静态代码块调用

动态成员变量初始化

非静态代码块调用

构造方法调用

以下供练习:

 1 public class TestPerson {
 2 
 3     public static void main(String[] args) {
 4         // TODO Auto-generated method stub
 5         Person person = new Person();
 6         Person person2 = new Person();
 7     }
 8 
 9 }
10 
11 class Person {
12     public final String name;
13     public int age;    
14 
15     public Person() {
16         System.out.println("无参构造方法");
17     }
18 
19     {
20         System.out.println("代码块2");
21     }
22 
23     {
24         System.out.println("代码块1");
25         name = "小明";
26     }
27 
28     static {
29         System.out.println("静态代码块2");
30     }
31 
32     static {
33         System.out.println("静态代码块1");
34     }
35 
36     
37 
38     public Person(int age) {
39         this.age = age;
40         //this.name = "";
41         System.out.println("构造age方法");
42     }
43 
44     public void goToSchool() {
45         System.out.println(name + "goToSchool方法");
46     }
47 }

结果:

静态代码块2
静态代码块1
代码块2
代码块1
无参构造方法
代码块2
代码块1
无参构造方法

posted @ 2018-03-17 18:26  不是植物  阅读(275)  评论(0编辑  收藏  举报