看代碼說結果
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.