如果我没有在代码中初始化count变量,而是让其默认值初始化,那么我的代码将正确显示count = 1。 但是,如果我在代码中将其初始化为0-> private static int count = 0,它将显示0。请问任何一个原因是什么?
class Singleton3 {
private final static Singleton3 obj = new Singleton3();
private static int count;
private Singleton3() {
count++;
}
public static Singleton3 getInstance() {
return obj;
}
public static int getCount() {
return count;
}
}
public class SingletonImplEagerInitialization {
public static void main(String[] args) {
Singleton3.getInstance();
Singleton3.getInstance();
Singleton3.getInstance();
Singleton3.getInstance();
Singleton3.getInstance();
System.out.println("count: " + Singleton3.getCount());
}
}