class Singleton{ private static Singleton instance=new Singleton(); public static int count; public static int count1=0; private Singleton(){ count++; count1++; } public static Singleton getInstance(){ return instance; } }public class SingleTonDemo { public static void main(String[] args) { Singleton instance=Singleton.getInstance(); System.out.println(instance.count); //1 System.out.println(instance.count1);//0 }
1 回答
慕运维8079593
TA贡献1876条经验 获得超5个赞
因为你变量初始化顺序的问题。
创建
Singleton
对象,此时count
,count1
都为1
private static Singleton instance = new Singleton();
静态初始化
count1
,这里又将count1
赋值为0
public static int count1 = 0;
你想要2个都得1将
instance
初始化放置在count1
下面即可。public static int count;
public static int count1 = 0; private static Singleton instance = new Singleton();
添加回答
举报
0/150
提交
取消