java中静态代码执行顺序

1.Java中静态变量只能在类主体中定义,不能在方法中定义。 静态变量属于类所有而不属于方法。

2.  静态块:用static申明,JVM加载类时执行,仅执行一次
  构造块:类中直接用{}定义,每一次创建对象时执行
执行顺序优先级:静态块>main()>构造块>构造方法
3. 类的加载顺序
  (1) 父类静态对象和静态代码块
  (2) 子类静态对象和静态代码块
  (3) 父类非静态对象和非静态代码块
  (4) 父类构造函数
  (5) 子类 非静态对象和非静态代码块
  (6) 子类构造函数

 4.例子(看了一目了然)

 1 class Root{
 2     static {
 3         System.out.println("Root的静态初始化块。");
 4     }
 5     {
 6         System.out.println("Root的普通初始化块。");
 7     }
 8     public Root(){
 9         System.out.println("Root的无参构造函数。");
10     }
11 }
12 
13 class Mid extends Root{
14     static {
15         System.out.println("Mid的静态初始化块。");
16     }
17     {
18         System.out.println("Mid的普通初始化块。");
19     }
20     public Mid() {
21         System.out.println("Mid的无参构造函数。");
22     }
23     public Mid(String msg) {
24     System.out.println("Mid的带参数构造函数,参数值为:" + msg);
25     }
26 }
27 
28 class Leaf extends Mid{
29     static {
30         System.out.println("Leaf的静态初始化块。");
31     }
32     {
33         System.out.println("Leaf的普通初始化块。");
34     }
35     public Leaf() {
36         super("Leaf传给Mid");
37         System.out.println("执行Leaf的构造函数。");    
38     }
39 }
40     
41 
42 public class staticTest {
43     public static void main(String[] args) {
44         new Leaf();
45         new Leaf();
46     }
47 }

执行结果

 注意:

静态初始化块仅在第一次使用类时执行初始化操作。上面例子中,第二次创建Leaf对象是,静态初始化块并没有执行。

原文地址:https://www.cnblogs.com/sjxbg/p/8831346.html