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"]
| Modifier | เข้าถึงจากนอก class | เข้าถึงใน subclass | ค่าเริ่มต้น |
|---|---|---|---|
public |
ได้ | ได้ | ใช่ |
private |
ไม่ได้ | ไม่ได้ | |
protected |
ไม่ได้ | ได้ |
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());
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 ใช้กำหนด 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 IUserService {
getUsers(): string[];
}
class UserService implements IUserService {
getUsers(): string[] {
return ["Ana", "Ben"];
}
}
const service = new UserService();
console.log(service.getUsers());
โดยที่ I คือจำนวน instance ทั้งหมด, C คือจำนวน class ที่นำมาสร้าง object, และ n คือจำนวน object เฉลี่ยต่อ class
private และ protected ต่างกันอย่างไรextends ใช้ทำอะไรimplements ใช้ตรวจอะไรใน class