[TypeScript] 객체 지향 설계를 위한 클래스

클래스의 주요 구성 요소

속성 (Properties)

클래스 내에 선언된 변수로, 각 인스턴스가 고유의 데이터를 보유할 수 있도록 합니다.

메서드 (Methods)

클래스에 정의된 함수들로, 객체의 행동이나 동작을 구현합니다.

생성자 (Constructor)

객체가 생성될 때 자동으로 호출되며, 인스턴스의 초기 상태(속성 값)를 설정합니다.

접근 제한자 (Access Modifiers)

  • public: 클래스 외부에서 자유롭게 접근 가능.
  • private: 클래스 내부에서만 접근할 수 있어, 데이터 은닉을 실현.
  • protected: 클래스와 그 하위 클래스 내에서만 접근 가능.

클래스의 기본 구조

클래스에서는 주요 구성 요소를 통해 객체의 설계도를 만들고, 필요할 때마다 인스턴스를 생성할 수 있습니다.

class CoffeeMachine {
  brand: string;

  constructor(brand: string) {
    this.brand = brand;
  }

  brew(): string {
    return `${this.brand} 커피머신이 맛있는 커피를 내리고 있습니다.`;
  }
}

const myMachine = new CoffeeMachine("네스프레소");
console.log(myMachine.brew());
// 출력: 네스프레소 커피머신이 맛있는 커피를 내리고 있습니다.

접근 제한자 활용하기

접근 제한자 요소를 활용해 클래스 내부 데이터를 제어합니다. 외부 접근을 제한하거나, 상속 시 특정 속성을 설정할 수 있습니다.

class Library {
  public name: string;
  private bookStock: number;

  constructor(name: string, initialStock: number) {
    this.name = name;
    this.bookStock = initialStock;
  }

  borrowBook(count: number): void {
    if (this.bookStock >= count) {
      this.bookStock -= count;
      console.log(`${count}권을 대여했습니다. 남은 재고: ${this.bookStock}`);
    } else {
      console.log("재고가 부족합니다.");
    }
  }

  checkStock(): number {
    return this.bookStock;
  }
}

const myLibrary = new Library("시립 도서관", 50);
myLibrary.borrowBook(3);
// 출력: 3권을 대여했습니다. 남은 재고: 47
console.log(`현재 재고: ${myLibrary.checkStock()}`);
// 출력: 현재 재고: 47

// myLibrary.bookStock = 100; // 오류: private 속성은 외부에서 접근 불가

상속으로 기능 확장

클래스 extends 키워드로 다른 클래스를 상속받아 기능을 확장할 수 있습니다. 부모 클래스의 속성과 메서드를 재사용하며, 필요 시 오버라이드로 동작을 재정의할 수 있습니다.

class Vehicle {
  constructor(public type: string) {}

  move(): string {
    return `${this.type}가 이동 중입니다.`;
  }
}

class Motorcycle extends Vehicle {
  speed: number;

  constructor(type: string, speed: number) {
    super(type); // 부모 생성자 호출
    this.speed = speed;
  }

  move(): string {
    return `${this.type}가 시속 ${this.speed}km로 질주합니다!`;
  }
}

const myBike = new Motorcycle("오토바이", 80);
console.log(myBike.move());
// 출력: 오토바이가 시속 80km로 질주합니다!

인터페이스와 결합한 클래스

클래스는 인터페이스를 구현하여 특정 구조를 강제할 수 있습니다.

interface Gadget {
  powerOn(): string;
  getStatus(): string;
}

class SmartWatch implements Gadget {
  batteryLevel: number;

  constructor(batteryLevel: number) {
    this.batteryLevel = batteryLevel;
  }

  powerOn(): string {
    return "스마트워치가 켜졌습니다.";
  }

  getStatus(): string {
    return `배터리 잔량: ${this.batteryLevel}%`;
  }
}

const myWatch = new SmartWatch(75);
console.log(myWatch.powerOn());
// 출력: 스마트워치가 켜졌습니다.
console.log(myWatch.getStatus());
// 출력: 배터리 잔량: 75%