Java教程

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 类初始化顺序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!