🎯 学习目标

  • 掌握类的继承语法
  • 理解方法重写和多态
  • 学会使用 super 调用父类方法
  • 了解继承的类型约束

📝 类继承

// 基类 class Animal { constructor(public name: string) {} speak(): string { return `${this.name} makes a sound`; } move(distance: number = 0): void { console.log(`${this.name} moved ${distance} meters`); } } // 派生类 class Dog extends Animal { constructor(name: string, public breed: string) { super(name); // 必须调用 super() } // 方法重写 speak(): string { return `${this.name} barks: Woof!`; } // 扩展父类方法 move(distance: number = 5): void { console.log('Running...'); super.move(distance); // 调用父类方法 } } const dog = new Dog('Buddy', 'Golden Retriever'); console.log(dog.speak()); // "Buddy barks: Woof!" dog.move(10); // Running... Buddy moved 10 meters

🔄 多态

// 多态:同一接口,不同实现 class Cat extends Animal { speak(): string { return `${this.name} meows`; } } // 多态使用 const animals: Animal[] = [ new Animal('Generic'), new Dog('Buddy', 'Labrador'), new Cat('Whiskers') ]; animals.forEach(animal => { console.log(animal.speak()); // Generic makes a sound // Buddy barks: Woof! // Whiskers meows }); // 多态函数 function makeSound(animal: Animal): void { console.log(animal.speak()); } makeSound(new Dog('Max', 'Beagle')); // Max barks: Woof! makeSound(new Cat('Luna')); // Luna meows
💡
多态优势

多态允许使用父类类型的引用指向子类对象,调用方法时会执行子类的实现,实现灵活的代码设计。

📝 本节小结

  • • 使用 extends 实现继承
  • • 子类构造函数必须调用 super()
  • • 方法重写实现多态
  • • super 调用父类方法