- class SingleTon {
-
- private static SingleTon singleTon = new SingleTon();
-
- public static int a;
-
- public static int b = 0;
-
- private SingleTon () {
-
- a++;
- b++;
- }
-
- public static SingleTon getInstance() {
-
- return singleTon;
- }
- }
- public class Test {
-
- public static void main(String[] args) {
-
- SingleTon singleTon = SingleTon.getInstance();
-
- System.out.println(" a is "+singleTon.a);
- System.out.println(" b is "+singleTon.b);
- }
-
- }
复制代码 求接输出结果:
答案及分析:
输出结果是:
a is 1
b is 0
分析:SingleTon 类是一个单例类,当在程序入口main方法中获得SingleTon 实例的时候,jvm会初始化所有静态变量,SingleTon = null,int a会赋值0,int b也会赋值0,然后SingleTon = new SingleTon(),在构造方法中a++,b++,a=1;b=1。程序这时候再往下执行,到了输出,调用a,这时候a没有被再次赋值,所以a就是1,但是b被再次赋值了b=0,所有b就是0 了。输出结果就是上面的结果。
|