当前位置: 技术问答>java相关
请那位高手帮我解释一下
来源: 互联网 发布时间:2015-07-09
本文导语: 请那位高手帮我解释一下class WaterSource{ private String s; WaterSource(){ System.out.println("WaterSource()"); s=new String("Constructed"); } public String toString(){return s;} } public class Sprinkler{ private String valve1,valve2,valve3,valve4; Water...
请那位高手帮我解释一下class WaterSource{
private String s;
WaterSource(){
System.out.println("WaterSource()");
s=new String("Constructed");
}
public String toString(){return s;}
}
public class Sprinkler{
private String valve1,valve2,valve3,valve4;
WaterSource source;
int i;
float f;
void print(){
System.out.println("valve1="+valve1);
System.out.println("valve2="+valve2);
System.out.println("valve3="+valve3);
System.out.println("valve4="+valve4);
System.out.println("i="+i);
System.out.println("f="+f);
System.out.println("source="+source);
}
public static void main(String[] args){
Sprinkler x=new Sprinkler();
x.print();
}
}这段程序,他的输出结果是:
valve1=null
valve2=null
valve3=null
valve4=null
i=0
f=0.0
source=null
我的意思是他为何是这个结果?
private String s;
WaterSource(){
System.out.println("WaterSource()");
s=new String("Constructed");
}
public String toString(){return s;}
}
public class Sprinkler{
private String valve1,valve2,valve3,valve4;
WaterSource source;
int i;
float f;
void print(){
System.out.println("valve1="+valve1);
System.out.println("valve2="+valve2);
System.out.println("valve3="+valve3);
System.out.println("valve4="+valve4);
System.out.println("i="+i);
System.out.println("f="+f);
System.out.println("source="+source);
}
public static void main(String[] args){
Sprinkler x=new Sprinkler();
x.print();
}
}这段程序,他的输出结果是:
valve1=null
valve2=null
valve3=null
valve4=null
i=0
f=0.0
source=null
我的意思是他为何是这个结果?
|
类变量如果没有初始化,会对变量设置默认值.
因value1,value2,value3,value4,i,f,source这些变量都没有初始化。所以系统都输出了它们的默认值
因value1,value2,value3,value4,i,f,source这些变量都没有初始化。所以系统都输出了它们的默认值
|
各自类型的默认值,
string 为null,整形为0,浮典型为0.0
string 为null,整形为0,浮典型为0.0