组合初始化
class Soap{
private String s;
Soap(){
System.out.println("Soap()");
s=new String ("Constructed");
}
public String toString(){
return s;
}
}
public class Bath{
Soap castille;
Bath(){
//castille=new Soap();
Soap castille=new Soap();
}
void print(){
System.out.println("castille="+castille);
}
public static void main(String[] args){
Bath b=new Bath();
b.print();
}
};
在Bath的构造器中,如果是Soap castille=new Soap();执行的结果是Soap() castille=null,
如果是castille=new Soap();执行的结果是Soap() castille=Constructed,两个不同的结果?请高手分别解释一下!为什么castille的值会是Constructed呢?
问题点数:20、回复次数:1Top
1 楼killme2008(为了生态平衡,请保护蛤蟆)回复于 2003-12-02 21:45:48 得分 20
Soap castille=new Soap()是局部变量,不会影响Bath的变量,那么castille就初始化为null
而castille=new Soap()就是为Bath的castille分配空间
一个是函数内局部,一个是类的内部,就这样Top




