class Dog {
protected color: string = "white" // color จะใช้ได้แค่ภายใน Class และ Subclass
printColor() {
console.log(`This dog is ${this.color}`)
}
}
class MyDog extends Dog {
printColor() {
console.log(`My dog is ${this.color}, and he's cute!`)
}
}
const d = new Dog()
d.color // ❌ เรียกใช้ไม่ได้ เพราะเป็น protected
d.printColor() // This dog is white
const e = new MyDog()
e.printColor() // My dog is white, and he's cute!
class Brain {
private cellCount: number // cellCount จะใช้ได้แค่ใน Class นี้
constructor(c: number) {
this.cellCount = c
}
countCells() {
console.log(`The brain has ${this.cellCount} cells`) // ✅
}
}
const brain = new Brain(84000)
console.log(brain.cellCount) // ❌ ไม่สามารถเรียกใช้ cellCount จากภายนอกคลาสได้
class BigBrain extends Brain {
doubleCells() {
// ❌ ไม่สามารถเรียกใช้ cellCount จาก Subclass ได้
this.cellCount = this.cellCount * 2
}
}