상속?
부모 클래스의 요소를 전부 다져오고, 필요한 부분만 추가하거나 오버라이딩 해서 사용할 수 있도록 하는 것.
공통적인 부분들을 부모클래스로 빼놓고 사용하면, 코드의 재사용성이 극대화됨.
여기서 다시, private과 protected
private
: 오로지 해당 클래스에서만 사용할 것.
protected
: 외부에서는 접근할 수 없지만 이 클래스를 상속한 클래스에서는 접근할 수 있다.
아래 코드 예시에서 라떼머신은 커피머신을 상속하지만, 커피머신에 있는
coffeBeans
변수는 private
속성이므로 자식 클래스에서도 직접 접근할 수 없다.코드 예시
- 커피머신에는
makeCoffee
함수가 정의되어 있다.
커피머신에서 정의한 makeCoffee 함수에서
grind()
, preheat()
, extract()
함수를 호출한다.- 라떼머신은 커피머신을 상속받는다.
- 라떼 머신에서는 커피머신의 커피에서 우유만 추가로 얹고 싶다.
부모의 함수를 그대로 호출한 뒤 마지막에 우유만 추가해서 라떼를 반환하도록 함수를 재정의한다.
오버라이딩 (재정의){ type CoffeeCup = { shots: number; hasMilk: boolean; }; interface CoffeeMaker { makeCoffee(shots: number): CoffeeCup; } class CoffeeMachine implements CoffeeMaker { private static BEANS_GRAMM_PER_SHOT: number = 7; // class level private coffeeBeans: number = 0; // instance (object) level constructor(coffeeBeans: number) { this.coffeeBeans = coffeeBeans; } static makeMachine(coffeeBeans: number): CoffeeMachine { return new CoffeeMachine(coffeeBeans); } fillCoffeeBeans(beans: number) { if (beans < 0) { throw new Error('value for beans should be greater than 0'); } this.coffeeBeans += beans; } clean() { console.log('cleaning the machine...🧼'); } private grindBeans(shots: number) { console.log(`grinding beans for ${shots}`); if (this.coffeeBeans < shots * CoffeeMachine.BEANS_GRAMM_PER_SHOT) { throw new Error('Not enough coffee beans!'); } this.coffeeBeans -= shots * CoffeeMachine.BEANS_GRAMM_PER_SHOT; } private preheat(): void { console.log('heating up... 🔥'); } private extract(shots: number): CoffeeCup { console.log(`Pulling ${shots} shots... ☕️`); return { shots, hasMilk: false, }; } makeCoffee(shots: number): CoffeeCup { this.grindBeans(shots); this.preheat(); return this.extract(shots); } } class CaffeLatteMachine extends CoffeeMachine { constructor(beans: number, public readonly serialNumber: string) { super(beans); } private steamMilk(): void { console.log('Steaming some milk... 🥛'); } makeCoffee(shots: number): CoffeeCup { const coffee = super.makeCoffee(shots); this.steamMilk(); return { ...coffee, hasMilk: true, }; } } const machine = new CoffeeMachine(23); const latteMachine = new CaffeLatteMachine(23, 'SSSS'); const coffee = latteMachine.makeCoffee(1); console.log(coffee); console.log(latteMachine.serialNumber); }