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

在父类中访问子类的成员变量

public class Father {

private String father;

public Father() {
Field fs[] = this.getClass().getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
Field f = fs[i];
System.out.println(f.getType().getName() + " " + f.getName());
}
}

}


public class Son extends Father {

private int age;
private String name;

public Son() {
super();
// TODO Auto-generated constructor stub
}

}


public class Test {

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
Son son = new Son();
}

}

这个是打印结果:
int age
java.lang.String name

请重点分析Father的构造方法this变量,解释一下打印出来的为什么是上面的结果?

我觉得的结果是:
java.lang.String name

------解决方案--------------------
楼主肯定是受了父类构造方法的影响。其实不然在类的构造时确实要先调用父类中的构造方法。但是父类的构造方法中用的是this,this代表的是当前对象的实例,而你是new Son自然this就代表Son了打印出Son类的成员变量一点也不奇怪