Java继承的初始化问题

public class Dervied extends Base {

private String name = "dervied";
    public Dervied() {
        tellName();
        printName();
    }
    public void tellName() {
        System.out.println("Dervied tell name: " + name);
    }
    public void printName() {
        System.out.println("Dervied print name: " + name);
    }
    public static void main(String[] args){
        new Dervied();
    }
}
class Base {
    private String name = "base";
    public Base() {
        tellName();
        printName();
    }
    public void tellName() {
        System.out.println("Base tell name: " + name);
    }
    public void printName() {
        System.out.println("Base print name: " + name);
    }
}
运行结果:
Dervied tell name: null
Dervied print name: null
Dervied tell name: dervied
Dervied print name: dervied

为什么会这样呢
并且无论修改Base的name为public还是protected,结果都是这样.
甚至代码改成这样,还是这个结果(Base类的name字段改成了basename)

public class Dervied extends Base {

private String name = "dervied";
    public Dervied() {
        tellName();
        printName();
    }
    public void tellName() {
        System.out.println("Dervied tell name: " + name);
    }
    public void printName() {
        System.out.println("Dervied print name: " + name);
    }
    public static void main(String[] args){
        new Dervied();
    }
}
class Base {
    public String basename = "base";
    public Base() {
        tellName();
        printName();
    }
    public void tellName() {
        System.out.println("Base tell name: " + basename);
    }
    public void printName() {
        System.out.println("Base print name: " + basename);
    }
}

后台一个大神一语道破
Base的构造函数中,调用的两个方法tellName和printName,因为继承的原因,应该执行的是子类的方法,而子类此时还没有初始化这个数据成员,所以显示为null.

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/7356130534dfc2a98c486859dc7566d7.html