public class StaticVariableTest
{
private static StaticVariableTest svt=new StaticVariableTest();
private static int count1;
private static int count2=0;
private StaticVariableTest()
{
count1++;
count2++;
}
public static StaticVariableTest getInstance()
{
return svt;
}
public static int getCount1()
{
return count1;
}
public static void setCount1(int count1)
{
StaticVariableTest.count1=count1;
}
public static int getCount2()
{
return count2;
}
public static void setCount2(int count2)
{
StaticVariableTest.count1=count2;
}
public static void main(String args[])
{
StaticVariableTest svt=StaticVariableTest.getInstance();
System.out.println("count1:"+svt.getCount1());
System.out.println("count2:"+svt.getCount2());
}
}
这个代码count1可以理解输出的是1,
但是count2为什么是0呢???
count1的初始默认值是0,
count2的初始值夜是0呀,为什么输出的会是0呢???

解决方案 »

  1.   

    你试试把private static int count2=0;改成private static int count2=3;你就能明白怎么回事儿了。
      

  2.   

    你去看看Thinking in Java里关于变量的创建与初始化吧。
      

  3.   

    因为
        private static StaticVariableTest svt=new StaticVariableTest();
        private static int count1;
        private static int count2=0;这三句话都是静态的,他们在类加载的时候被初始化(执行),执行顺序为代码书写的顺序,
    所以,在第一句话将count1和2都+1后,
    在第三句话的时候,count2又被初始化成0了。
    而第二句话,优于count1没有明确赋值,所以,已经在构造函数中被初始化过的,不再重复初始化。你可以将这三句话调整为:    private static int count1;
        private static int count2=0;
        private static StaticVariableTest svt=new StaticVariableTest();就明白了。