학습
TypeScript 클래스 상속
TypeScript 클래스 상속 — 중급
클래스 상속
1. 도입 (왜 배워야 하는가)
클래스 상속은 객체 지향 프로그래밍(OOP)의 핵심 개념 중 하나로, 기존 클래스를 기반으로 새로운 클래스를 생성할 수 있는 기능입니다. 실무에서는 코드의 재사용성을 높이고, 유지보수를 용이하게 하며, 다형성을 활용할 수 있습니다. 예를 들어, 쇼핑몰의 여러 상품 클래스가 모두 공통적으로 Product라는 클래스를 상속받을 수 있습니다. 이를 통해 상품의 공통 속성을 정의하고, 각 상품별로 특화된 기능을 추가하는 방식으로 구현할 수 있습니다.
만약 클래스 상속을 모른다면, 중복된 코드를 작성하게 되어 유지보수가 어려워지고, 코드의 가독성 및 효율성이 떨어질 수 있습니다.
2. 핵심 개념 설명
클래스 상속이란, 한 클래스가 다른 클래스의 속성과 메서드를 물려받는 것을 의미합니다. 이를 통해 코드의 재사용성을 높이고, 객체 간의 관계를 명확히 할 수 있습니다.
실생활 비유
클래스 상속을 자동차의 모델로 비유할 수 있습니다. 차량이라는 기본 클래스를 가지고, 세단, SUV, 트럭 같은 다양한 모델이 이를 상속받아 각자의 특성과 기능을 추가하는 방식입니다. 기본적인 속성(예: 바퀴 수, 엔진 타입)은 차량 클래스에 정의되고, 각 모델은 자신만의 고유 기능을 구현합니다.
관련 용어 정리
| 용어 | 설명 |
|---|---|
| 부모 클래스 | 다른 클래스가 상속받는 클래스 |
| 자식 클래스 | 부모 클래스를 상속받는 클래스 |
| 메서드 오버라이딩 | 부모 클래스의 메서드를 자식 클래스에서 재정의하는 것 |
3. 기본 코드 예제
아래는 기본적인 클래스 상속의 사용법을 보여주는 코드입니다.
class Animal {
constructor(public name: string) {}
speak(): string {
return ${this.name}가 소리를 냅니다.;
}
}
class Dog extends Animal {
speak(): string {
return ${this.name}가 멍멍 소리를 냅니다.;
}
}
const dog = new Dog("바둑이");
console.log(dog.speak());
실행 결과
바둑이가 멍멍 소리를 냅니다.
코드 한 줄씩 동작 설명
class Animal { ... }:Animal이라는 부모 클래스를 정의합니다.constructor(public name: string) {}: 클래스의 생성자를 정의하여,name속성을 초기화합니다.speak(): string { ... }: 기본적인speak메서드를 정의합니다.class Dog extends Animal { ... }:Dog라는 자식 클래스를 정의하고,Animal클래스를 상속받습니다.speak(): string { ... }:Animal클래스의speak메서드를 오버라이딩하여 강아지의 소리를 정의합니다.const dog = new Dog("바둑이");:Dog클래스의 인스턴스를 생성합니다.console.log(dog.speak());: 강아지의 소리를 출력합니다.
4. 실전 활용 예제
예제 1: 쇼핑몰에서 장바구니를 구현할 때
쇼핑몰의 Item 클래스를 만들고, 이를 상속받는 Book, Electronics 클래스를 정의합니다.
class Item {
constructor(public name: string, public price: number) {}
getDetails(): string {
return ${this.name}의 가격은 ${this.price}원입니다.;
}
}
class Book extends Item {
constructor(name: string, price: number, public author: string) {
super(name, price);
}
getDetails(): string {
return ${super.getDetails()} 저자: ${this.author};
}
}
class Electronics extends Item {
constructor(name: string, price: number, public warranty: number) {
super(name, price);
}
getDetails(): string {
return ${super.getDetails()} 보증기간: ${this.warranty}개월;
}
}
예제 2: 게임 캐릭터 생성
게임에서 Character 클래스를 만들고, 이를 상속받는 Warrior, Mage 클래스를 정의합니다.
class Character {
constructor(public name: string, public health: number) {}
attack(): string {
return ${this.name}이(가) 공격합니다.;
}
}
class Warrior extends Character {
constructor(name: string, health: number) {
super(name, health);
}
attack(): string {
return ${this.name}이(가) 검으로 공격합니다.;
}
}
class Mage extends Character {
constructor(name: string, health: number) {
super(name, health);
}
attack(): string {
return ${this.name}이(가) 마법으로 공격합니다.;
}
}
5. 흔한 실수와 주의사항
실수 1: 부모 클래스의 메서드 호출을 잊음
class Cat extends Animal {
speak(): string {
return "고양이가 야옹 소리를 냅니다.";
}
}
super.speak()를 호출하지 않아 기본적인 동작을 누락할 수 있습니다.class Cat extends Animal {
speak(): string {
return super.speak() + " 고양이가 야옹 소리를 냅니다.";
}
}
실수 2: 잘못된 상속 구조
super()를 호출하여 부모 클래스의 생성자를 초기화해야 합니다.