public class People {
public String getName() { return "people"; }
}
public class Student extends People {
public String getName() { return "student"; }
}
public static void main(String[] args) {
People p = new People(); // 輸出: people
Student s = new Student(); // 輸出: student
People pp = new Student(); // 輸出: student ← 關鍵:多態生效
}
子類方法成功覆寫父類方法,向上轉型時調用的是子類實現。
public class People { protected String name = "people"; }
public class Student extends People { protected String name = "student"; }
public static void main(String[] args) {
People p = new People(); // 輸出: people
Student s = new Student(); // 輸出: student
People pp = new Student(); // 輸出: people ← 關鍵:父類變數
}
變數遮蔽只是「半吊子的覆寫」:向上轉型後訪問的是父類變數,違背多態預期,極易導致錯誤。
public class People {
protected String name = "people";
public String getName() { return name; }
}
public class Student extends People {
protected String name = "student";
public String getName() { return name; } // 覆寫方法返回自類變數
}
People pp = new Student();
System.out.println(pp.getName()); // 輸出: student ← 正確多態
透過方法覆寫包裝變數訪問,才能真正實現「將具體對象泛化為通用對象」的多態目標。