Java-JVM 类的初始化

public class Test {
    protected static final Logger logger = LoggerFactory.getLogger(Test.class);

    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance();
        logger.info("counter1:" + singleton.counter1);
        logger.info("counter2:" + singleton.counter2);
    }
}

class Singleton {
    private static Singleton singleton = new Singleton();
    public static int counter1;
    public static int counter2 = 0;

    private Singleton() {
        counter1++;
        counter2++;
    }

    public static Singleton getInstance() {
        return singleton;
    }
}

Singleton singleton = Singleton.getInstance();这行代码首先给Singleton中的变量赋予默认的初始值:

即:private static Singleton singleton的singleton赋予默认初始值null、

public static int counter1 的counter1赋予默认初始值0、

public static int counter2 的counter2赋予默认初始值0(不是显式的0)、

然后会显式地给变量赋值:

private static Singleton singleton的singleton赋予new Singleton(),此时会执行Singleton类的构造函数:

private Singleton(){

counter1++;

counter2++;

}

counter1 = 1;

counter2 = 1;

接着给counet1、counter2显式赋值

public static int counter1 ;

public static int counter2 = 0;

由于counter1没有显式值

所以赋值完成后counter1 = 1、counter2 = 0;

最后输出为counter1 = 1、counter2 = 0;

如果把 private static Singleton singleton = new Singleton();放在 public static int counter2 = 0;的后面,则会输出counter1 = 1、counter2 = 1;

原文地址:https://www.cnblogs.com/y8932809/p/8990975.html