代碼:
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
為什麼會是null????
1、首先private是不會繼承到新的對象裡,所以不會出現“base”。
2、由於重寫的緣故,在執行super的構造函數是,還是調用的子類方法,此時成員變量未初始化。