大家帮我分析分析
public class StaticTest
{
private static StaticTest st = new StaticTest();
public static int count1;
public static int count2 = 0;
private StaticTest()
{
count1++;
count2++;
}
public static StaticTest getInstance()
{
return st;
}
public static void main(String[] args)
{
StaticTest st = StaticTest.getInstance();
System.out.println("count1: " + st.count1);
System.out.println("count2: " + st.count2);
}
}
看看程序的结果为什么是1,0
这是我在听风中叶老师视频上看到的一段代码,但是我还是有不明白的地方?
大家看看
------解决方案--------------------这句是static,
private static StaticTest st = new StaticTest();
且在以下两句之前
public static int count1;
public static int count2 = 0;
就是说先执行
count1++;
count2++;
然后再
public static int count1;
public static int count2 = 0;
------解决方案--------------------换个顺序就清楚了
public static int count1;
public static int count2 = 0;
private static StaticTest st = new StaticTest();
------解决方案--------------------new StaticTest()时执行:
count1++;
count2++;
然后又遇到
public static int count1;
public static int count2 = 0;
count2又被置为0了。
把“public static int count2=0;”中的“=0”去掉,再试试看?