หัวข้อ 4: Class, Inheritance และ Access Modifier

คำจำกัดความ

Class คือ blueprint สำหรับสร้าง object ส่วน Inheritance คือการสืบทอดคุณสมบัติจาก class แม่ไปยัง class ลูก

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#458588", "primaryTextColor": "#fbf1c7", "primaryBorderColor": "#fabd2f", "lineColor": "#a89984", "secondaryColor": "#b8bb26", "tertiaryColor": "#d3869b", "background": "#282828", "mainBkg": "#3c3836", "textColor": "#ebdbb2"}}}%%
flowchart TD
  A["Animal
Base Class"] --> B["Dog
Subclass"] A --> C["Cat
Subclass"] B --> D["Instance
dog object"] C --> E["Instance
cat object"]

Access Modifier

Modifier เข้าถึงจากนอก class เข้าถึงใน subclass ค่าเริ่มต้น
public ได้ ได้ ใช่
private ไม่ได้ ไม่ได้
protected ไม่ได้ ได้

Class และ Constructor

class Animal {
  public name: string;
  protected species: string;
  private age: number;

  constructor(name: string, species: string, age: number) {
    // กำหนดค่าเริ่มต้นให้ instance
    this.name = name;
    this.species = species;
    this.age = age;
  }

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

  protected getSpecies(): string {
    return this.species;
  }
}

const animal = new Animal("Milo", "Unknown", 2);
console.log(animal.speak());

Inheritance และ super()

class Dog extends Animal {
  constructor(name: string, age: number) {
    // เรียก constructor ของ class แม่
    super(name, "Dog", age);
  }

  public bark(): string {
    return `${this.name} barks as ${this.getSpecies()}`;
  }
}

const dog = new Dog("Lucky", 3);
console.log(dog.bark());

Abstract Class

Abstract Class ใช้กำหนด blueprint ที่ subclass ต้อง implement

abstract class Repository<T> {
  abstract findAll(): T[];
}

class UserRepository extends Repository<string> {
  findAll(): string[] {
    return ["Ana", "Ben"];
  }
}

const repo = new UserRepository();
console.log(repo.findAll());

Interface กับ Class

interface IUserService {
  getUsers(): string[];
}

class UserService implements IUserService {
  getUsers(): string[] {
    return ["Ana", "Ben"];
  }
}

const service = new UserService();
console.log(service.getUsers());

สมการจำนวน Instance

I = C × n

โดยที่ I คือจำนวน instance ทั้งหมด, C คือจำนวน class ที่นำมาสร้าง object, และ n คือจำนวน object เฉลี่ยต่อ class

แบบทดสอบหลังเรียน

  1. Constructor ใช้ทำอะไร
  2. private และ protected ต่างกันอย่างไร
  3. extends ใช้ทำอะไร
  4. Abstract class เหมาะกับกรณีใด
  5. implements ใช้ตรวจอะไรใน class

กลับสัปดาห์ที่ 6