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; } } public class TestSingleton { public static void main(String[] args) { Singleton s = Singleton.getInstance(); System.out.println(Singleton.counter1); System.out.println(Singleton.counter2); } }
输出结果是1,0
为什么
Java对于静态成员变量的初始化,分解为两步执行。
1. 根据静态成员变量在代码中的先后次序进行声明并赋值为缺省值2. 在静态块内依次为变量进行赋值