java中类成员初始化顺序

java中初始化类成员方法包括:

1.显示域初始化,比如public int a=1;public static int b=1;

2.初始化块,分为普通初始化块,静态初始化块;

3.构造函数。

 

初始化的时候,首先是静态类的初始化方式执行,然后才是普通初始方式执行,

并且初始化块总是先于构造函数执行,显式域初始化与初始化块的执行顺序按照代码中出现的顺序执行。

  • 显式静态域初始化先于静态初始化块
public class Hello{
    
    public static int staticA=1;
    public static int staticB;
       
    static{
        System.out.println("Static Inital Block Start");
        staticB=2;
        PrintAB();
        System.out.println("Static Inital Block End\n");
    }
    
    public static void PrintAB(){
        System.out.println("staticA:"+staticA);
        System.out.println("staticB:"+staticB);
    }

    public Hello(){
        Hello.PrintAB();
    }

    public static void main(String[] args){
        Hello h=new Hello();
    }
}

输出:

Static Inital Block Start
staticA:1
staticB:2
Static Inital Block End
 
staticA:1
staticB:2
  • 显式静态域初始化后于静态初始化块

 

public class Hello{
    
    public static int staticB;

    static{
        System.out.println("Static Inital Block Start");
        staticB=2;
        PrintAB();
        System.out.println("Static Inital Block End\n");
    }
    public static int staticA=1;
    public static void PrintAB(){
        System.out.println("staticA:"+staticA);
        System.out.println("staticB:"+staticB);
    }

    public Hello(){
        Hello.PrintAB();
    }

    public static void main(String[] args){
        Hello h=new Hello();
    }
}

 输出:

Static Inital Block Start
staticA:0
staticB:2
Static Inital Block End
 
staticA:1
staticB:2
  • 显式静态域初始化与初始化块按照出现顺序执行,最后执行构造函数,

  注意noStaticD在两个构造快中间初始化,第一个初始化块打印时noStaticD=0,第二个块中变为1

输出:

NoStatic Inital Block for noStaticC Start
noStaticC:1
noStaticD:1
noStaticE:1
noStaticF:0
NoStatic Inital Block for noStaticC End

Constructor Start
noStaticC:1
noStaticD:1
noStaticE:1
noStaticF:1
Constructor END

 

posted on 2018-10-27 17:42  Lv Jianwei  阅读(465)  评论(0编辑  收藏  举报