JAVA繼承的初始化問題

壹頁書發表於2015-08-28
看程式碼說結果
  1. public class Dervied extends Base {
  2.     private String name = "dervied";
  3.     public Dervied() {
  4.         tellName();
  5.         printName();
  6.     }
  7.     public void tellName() {
  8.         System.out.println("Dervied tell name: " + name);
  9.     }
  10.     public void printName() {
  11.         System.out.println("Dervied print name: " + name);
  12.     }
  13.     public static void main(String[] args){
  14.         new Dervied();
  15.     }
  16. }
  17. class Base {
  18.     private String name = "base";
  19.     public Base() {
  20.         tellName();
  21.         printName();
  22.     }
  23.     public void tellName() {
  24.         System.out.println("Base tell name: " + name);
  25.     }
  26.     public void printName() {
  27.         System.out.println("Base print name: " + name);
  28.     }
  29. }
執行結果:
Dervied tell name: null
Dervied print name: null
Dervied tell name: dervied
Dervied print name: dervied

為什麼會這樣呢
並且無論修改Base的name為public還是protected,結果都是這樣.
甚至程式碼改成這樣,還是這個結果(Base類的name欄位改成了basename)

  1. public class Dervied extends Base {
  2.     private String name = "dervied";
  3.     public Dervied() {
  4.         tellName();
  5.         printName();
  6.     }
  7.     public void tellName() {
  8.         System.out.println("Dervied tell name: " + name);
  9.     }
  10.     public void printName() {
  11.         System.out.println("Dervied print name: " + name);
  12.     }
  13.     public static void main(String[] args){
  14.         new Dervied();
  15.     }
  16. }
  17. class Base {
  18.     public String basename = "base";
  19.     public Base() {
  20.         tellName();
  21.         printName();
  22.     }
  23.     public void tellName() {
  24.         System.out.println("Base tell name: " + basename);
  25.     }
  26.     public void printName() {
  27.         System.out.println("Base print name: " + basename);
  28.     }
  29. }

後臺一個大神一語道破
Base的建構函式中,呼叫的兩個方法tellName和printName,因為繼承的原因,應該執行的是子類的方法,而子類此時還沒有初始化這個資料成員,所以顯示為null.

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-1784890/,如需轉載,請註明出處,否則將追究法律責任。

相關文章