Java类中成员初始化顺序

 1 package com.szxy;
 2 
 3 /**
 4  * 
 5  * @author Momentonly
 6  *
 7  */
 8 public class InitClassTest {
 9     public static void main(String[] args) {
10         new B();    
11     }
12 }
13 class A{
14     static A a = new A();                        //1)
15     static{
16         System.out.println("A:static");          //2)
17     }
18     C c = new C();                               //5)
19     {                                            //6)
20         System.out.println("A:not static");      
21     }
22     public A() {                                 //7)
23         System.out.println("A:constructor");
24     }
25 }
26 class B extends A {
27     static{
28         System.out.println("B:static");          //3)
29     }
30     static B b = new B();                        //4)
31     {                                            //8)
32         System.out.println("B:not static");
33     }
34     public B() {                                 //9)
35         System.out.println("B:constructor");
36     }
37 }
38 class C{
39     public C() {
40         System.out.println("C");
41     }
42 }

 

console打印结果: 

C                     //1)
A:not static          //1)
A:constructor         //1)
A:static              //2)
B:static              //3)
C                     //4)
A:not static          //4)
A:constructor         //4)
B:not static          //4)
B:constructor         //4)
C                     //5)
A:not static          //6)
A:constructor         //7)
B:not static          //8)
B:constructor         //9)

 

根据打印结果:父类静态变量(静态代码块)-> 子类静态变量(静态代码块)

-> 父类成员变量(非静态代码块)-> 父类构造方法 ->子类成员变量(非静态代码块)

-> 子类构造方法

 

ps:静态变量和静态代码块属于平级,谁在前谁先初始化;

非静态代码块和成员变量属于平级,谁在前谁先初始化

 posted on 2020-04-06 17:13  Momentonly  阅读(193)  评论(0)    收藏  举报