编程语言
首页 > 编程语言> > java 类初始化顺序

java 类初始化顺序

作者:互联网

 

public class StaticClass {
    static int c1=0;
    private static StaticClass staticClass = new StaticClass();
    static int c2=1;
    static int c3=3;
    static {
        c3++;
    }
    private StaticClass(){
        c1++;
        c2++;
        ++c3;
    }
    static StaticClass getInstance(){
        return  staticClass;
    }

}
class Test{
    public static void main(String[] args) {
        StaticClass staticClass = StaticClass.getInstance();
        System.out.println("c1:"+StaticClass.c1);
        System.out.println("c2:"+StaticClass.c2);
        System.out.println("c3:"+StaticClass.c3);
    }
}

 

 

结果:

count1=1;count2=1;count3=4

静态变量/代码块 -> 实例变量/代码块 -> 构造函数

( 静态代码只加载一次)

标签:初始化,顺序,java,++,StaticClass,static,c3,c2,c1
来源: https://www.cnblogs.com/code-learning/p/16585428.html