java小问题,请高人指点,谢谢

class chinese
{
static chinese example = new chinese();
static int count=1;
private chinese()
{
System.out.println(++count);
}

static
{
count=3;
System.out.println("static code");
}
public static chinese get()
{
return example;
}
}

class testchinese
{
public static void main(String[] args)
{

chinese ch1=chinese.get();
chinese ch2=chinese.get();
System.out.println(ch1==ch2);

}
}

为什么在执行这个程序时,count的返回值是1,还有为什么屏幕先显示的是1,而不是static code
完整的结果是
1
static code
ture

仔细的阅读thinking in java和实验得出:
静态对象创建static chinese example=new chinese();的执行是在所有初始化,静态块之前执行的。当创建出这个对象后,再执行静态块,再初始化静态变量,再非静态变量,再构造方法!
1的来历(我的理解):
最最先执行static chinese example=new chinese();
那么此时我们还只定义了一个count成员变量,既然他是成员变量,java虚拟机自动赋值给0;
然后再构造这个static对象,打印1;
理解清楚这里了,就容易了!
接着就是执行静态块,打印出static code
然而你的get()方法里指的对象相同,所以为true。
提供个人试验方法:
一,注释掉static chinese example=new chinese();
public static chinese get()
{
return example;
}
return语句为 return new chinese();
二,定义另一个变量q测试
static int q=5;
private chinese()
{
System.out.println(++q);
}

以上纯属个人观点,但有强力的后盾支持,如想更加确切的了解,请大师级人物回帖!!!!
温馨提示:内容为网友见解,仅供参考
第1个回答  2009-07-25
静态块是在初始化之前执行的,也就是说在你new这个类的时候,静态块已经执行。但是你所有的方法都是静态方法,所以当你调用的时候, System.out.println(ch1==ch2);
为真的时候,显示1
第2个回答  2009-07-25
System.out.println(ch1==ch2);
ch1==ch2的返回值是TRUE(1)
相似回答
大家正在搜