日期:2014-05-20  浏览次数:20830 次

想了半天没想明白的问题高手帮忙啊!!!
class   Watersource   {
private   String   s;
Watersource()
{
System.out.println( "Watersource() ");
s=new   String( "Constructed ");
}
public   String   toString(){return   s;
}
}

public   class   SprinkerSystem{
private   String   valve1,valve2,valve3,valve4;
private   Watersource   source;
private   int   i;
private   float   f;
public   String   toString(){
return
"valvel1= "+valve1+ "\n "+
"valvel2= "+valve2+ "\n "+  
"valvel3= "+valve3+ "\n "+
"valvel4= "+valve4+ "\n "+
"i= "+i+ "\n "+
"f= "+f+ "\n "+
"source= "+source;  
}
public   static   void   main   (String[]   args)   {
SprinkerSystem   Sprinker=new   SprinkerSystem();
System.out.println(Sprinker);
      }
}
结果  
valvel1=null
valvel2=null
valvel3=null
valvel4=null
i=0
f=0.0
source=null

--------------------------------------

SprinkerSystem   Sprinker=new   SprinkerSystem();
System.out.println(Sprinker);
SprinkerSystem类中没有任何方法体,只是创建了一个对象,然后输出对象。可结果为什么会是那样?



------解决方案--------------------
类实例化的时候会将成员进行初始化,对象类型的就初始化为null,primitive类型的就初始化为对应的零值
------解决方案--------------------
SprinkerSystem里面覆盖了toString(),你打印SprinkerSystem的实例Sprinker时,由于它是个object而打印object时会自动调用object.toString()作为输出结果。