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

关于java中constructor的一个问题


class Tester{

String s1 = "Hello World";
String s2;

Tester(){
 s2 = "New World";

}
}
public class Constructor {

public static void main(String [] args){
Tester t = new Tester();
System.out.println(t.s2);
System.out.println(t.s1);
}
}
运行结果:
New World
Hello World

但如果改成
class Tester{

String s1 = "Hello World";
String s2;

Tester(){
String s2 = "New World";

}
}
public class Constructor {

public static void main(String [] args){
Tester t = new Tester();
System.out.println(t.s2);
System.out.println(t.s1);
}
}
运行结果:
null
Hello World

请问为什么多了个String的定义constructor给的值就为空了呢?
------解决方案--------------------
class Tester
{

String s1 = "Hello World";
String s2;                   //你调用的是这里的s2,这里的s2没有赋值,默认为null;

Tester()
{
String s2 = "New World"; //这里的s2是你新定义的对象,和上面的s2不是同一个对象;

}
}

public class Constructor
{

public static void main(String[] args)
{
Tester t = new Tester();
System.out.println(t.s2); 
System.out.println(t.s1);
}
}