Week 02 · Day 06 — TypeScript 繼承與介面

學習目標

  • extends 實作類別繼承
  • 覆寫(override)父類別方法
  • implements 讓類別符合介面

重點

繼承(extends)

class Animal {
  constructor(public name: string) {}

  speak(): string {
    return `${this.name} makes a sound`;
  }
}

class Dog extends Animal {
  speak(): string {
    return `${this.name} barks`;   // 覆寫父類別方法
  }
}

const dog = new Dog("Rex");
dog.speak(); // "Rex barks"

介面與實作(implements)

interface Printable {
  print(): void;   // 只描述形狀,不含實作
}

class Document implements Printable {
  constructor(public title: string) {}

  print(): void {
    console.log(`Printing ${this.title}`);
  }
}
- interface 定義「必須有什麼」,class implements 保證提供實作 - 少了 print() 就會編譯錯誤

類別 vs 介面 | 型別 | 用途 | 要不要實作 | |------|------|-----------| | interface | 描述物件的形狀 | 不用,只是契約 | | class | 建立實際物件 | 要,含實作 |

實作

interface Shape {
  area(): number;
}

class Circle implements Shape {
  constructor(public radius: number) {}
  area(): number {
    return Math.PI * this.radius ** 2;
  }
}

class Square implements Shape {
  constructor(public side: number) {}
  area(): number {
    return this.side ** 2;
  }
}

// 多型:不管圓或方,只要有 area()
const shapes: Shape[] = [new Circle(2), new Square(3)];
shapes.forEach(s => console.log(s.area()));

作業

  • 建立 AnimalDog 繼承層級,並覆寫 speak()
  • 建立一個 Printable 介面並用 class 實作
  • 說出 extendsimplements 的差別