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

请大家帮我看看这道java题
public class BaseTest {
public String name;


public BaseTest() {
super();
}


public BaseTest(String name) {
super();
this.name = name;
}




}
public class Son extends BaseTest{


public Son() {
// TODO 自动生成构造函数存根
super("xxoo");
System.out.println(this.name);

this.name="xx";
}


}
public class TestSon {


/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
Son son=new Son();
System.out.println(son.name);


BaseTest bt=new BaseTest();

System.out.println(bt.name);


}


}
为什么输出的结果是:
xxoo
xx
null
------解决方案--------------------
Son son = new Son();的时候会调用Son的构造方法,即
public Son() {
// TODO 自动生成构造函数存根
super("xxoo");
System.out.println(this.name);

this.name="xx";
}[/code构造方法中先调用父类的构造方法即[code=java]public BaseTest(String name) {
super();
this.name = name;
}
在这里,son的成员变量name被赋值为xxoo,所以System.out.println(this.name)结果是xxoo,然后name又被赋值为xx,此事System.out.println(son.name)结果当然是xx;再后边创建父类的对象,父类的构造方法没有对其name成员变量进行赋值,System.out.println(bt.name)打印出的当然是null