繼承是面向對象編程(OOP)的三大支柱之一(封裝、繼承、多態)。在 Java 中,通過 extends 關鍵字實現類繼承:
// 父類:動物
class Animal {
void eat() { System.out.println("動物進食"); }
void sleep() { System.out.println("動物睡眠"); }
void breathe() { System.out.println("動物呼吸"); }
}
// 子類:魚類繼承動物
class Fish extends Animal {
// 自動擁有 eat()、sleep()、breathe() 方法
}
public class InheritanceDemo {
public static void main(String[] args) {
Animal animal = new Animal();
Fish fish = new Fish();
animal.breathe(); // 輸出:動物呼吸
fish.breathe(); // 輸出:動物呼吸(繼承自父類)
}
}
子類重新定義父類方法,實現差異化行為:
class Fish extends Animal {
@Override // 編譯器檢查註解,防止拼寫錯誤
void breathe() {
System.out.println("魚類用鰓呼吸"); // 子類專有實現
}
void swim() {
System.out.println("魚類游動");
}
}
public class OverrideDemo {
public static void main(String[] args) {
Animal animal = new Animal();
Fish fish = new Fish();
animal.breathe(); // 動物呼吸
fish.breathe(); // 魚類用鰓呼吸(多態調用子類方法)
fish.swim(); // 魚類游動(子類新增方法)
}
}
| 規則 | 說明 |
|---|---|
| 方法簽名一致 | 方法名、參數列表、返回類型必須完全相同(Java 5+ 支持协变返回類型) |
| 權限不得降低 | 子類方法訪問修飾符 ≥ 父類(public > protected > default > private) |
| 異常不得擴大 | 子類拋出的受檢異常 ⊆ 父類拋出的受檢異常 |
| final 方法不可覆蓋 | 父類 final 方法禁止重寫 |
| static 方法不可覆蓋 | 靜態方法屬於類,非實例,屬於方法隱藏 |
| 構造方法不可繼承 | 子類需自行定義構造器,通過 super() 調用父類構造器 |
class Bird extends Animal {
@Override
void breathe() {
super.breathe(); // 調用父類版本:輸出「動物呼吸」
System.out.println("鳥類用肺呼吸"); // 子類擴展
}
Bird(String name) {
super(); // 顯式調用父類無參構造器(可省略)
this.name = name;
}
}
class Animal {
String type;
Animal() { System.out.println("Animal 無參構造"); }
Animal(String type) { this.type = type; System.out.println("Animal 有參構造: " + type); }
}
class Dog extends Animal {
String breed;
Dog() { System.out.println("Dog 無參構造"); }
Dog(String breed) {
super("哺乳類"); // 必須第一行調用父類構造器
this.breed = breed;
System.out.println("Dog 有參構造: " + breed);
}
}
// 執行 new Dog("哈士奇") 輸出順序:
// Animal 有參構造: 哺乳類
// Dog 有參構造: 哈士奇
Animal a1 = new Dog(); // 向上轉型
Animal a2 = new Bird();
Animal a3 = new Fish();
a1.breathe(); // 動態綁定調用 Dog.breathe()
a2.breathe(); // 調用 Bird.breathe()
a3.breathe(); // 調用 Fish.breathe()
// 向下轉型(需 instanceof 守衛)
if (a1 instanceof Dog) {
Dog d = (Dog) a1;
d.swim(); // 子類特有方法
}
HAS-A 通常優於 IS-A,降低耦合protected,考慮 final 限制private 方法對子類不可見,子類同名方法為新方法extends 實現類繼承,支持代碼復用與多態。核心要點:單繼承、方法覆蓋規則、super 訪問父類、構造器鏈、多態動態綁定。實戰中遵循「優先組合、謹慎繼承、設計文檔化」原則,構建可維護的類層次結構。