刚开始学java
这一题具体的输出过程是怎样的啊,个人主观感觉只有Dervied的构造函数,
题目如下
class Base {
private String name = "base";
public Base() {
tellName();}
public void tellName() {
System.out.println("Base tell name: " + name); }
}
public class Dervied extends Base {
private String name = "dervied";
public Dervied() {
tellName();}
public void tellName() {
System.out.println("Dervied tell name: " + name);}
public static void main(String[] args){
new Dervied();
}}
输出结果
Dervied tell name: null
Dervied tell name: dervied
(1) 子类 Dervied 隐含 调用了父类的构造函数 super();
public Dervied() {
super();
tellName();
}
(2)子类 Dervied 重写了 tellName方法, 所以 子类调用父类构造方法 ,执行的 tellName 方法,实际还是子类的 tellName 方法。
(3)子类调用 父类构造方法,执行 tellName 方法时, 子类的name变量还没有初始化, name变量这个时候 就是 null;所以输出了 第一行的是null; 然后 子类的name变量开始初始化,调用子类的 tellName 方法,输出了 dervied。
变量初始化 和 构造方法的执行顺序等等,看看这篇博文,实践一下:
如有帮助,欢迎采纳哈!