← 홈페이지 5강 목록으로
🏛️
EPISODE 04
constructor · public/private · 상속 · abstract · implements

클래스

TypeScript 클래스 — 매개변수 프로퍼티 축약, 접근 제어자(public/private/protected/readonly), 상속(extends/super), 추상 클래스(abstract), 인터페이스 구현(implements)을 익힙니다.

classprivateabstractimplements
소요 시간
45분
난이도
📊 중급
선수 조건
🎯 ts-03
결과물
캡슐화·상속·추상화가 적용된 OOP 코드

이 강의에서 배우는 것

  • 1constructor와 매개변수 프로퍼티 축약을 사용한다
  • 2public/private/protected/readonly를 적절히 적용한다
  • 3extends와 super로 상속한다
  • 4abstract로 추상 클래스를 만든다
  • 5implements로 인터페이스를 구현한다

1. 클래스 선언

typescript
class Person {
  name: string;
  age: number;

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

  greet(): string {
    return `안녕하세요, 저는 ${this.name}입니다.`;
  }
}

매개변수 프로퍼티 (축약)

typescript
class Person {
  // constructor 매개변수에 접근 제어자 → 프로퍼티 자동 선언/할당
  constructor(
    public name: string,
    private age: number,
  ) {}
}

2. 접근 제어자

제어자접근 범위
public어디서나 (기본값)
private클래스 내부만
protected클래스 + 자식 클래스
readonly초기화 후 변경 불가
typescript
class BankAccount {
  private balance: number;
  readonly accountId: string;

  constructor(initialBalance: number) {
    this.balance = initialBalance;
    this.accountId = `ACC-${Date.now()}`;
  }

  getBalance(): number { return this.balance; }

  deposit(amount: number): void {
    if (amount <= 0) throw new Error('금액은 양수여야 합니다.');
    this.balance += amount;
  }
}

3. 상속 (extends)

typescript
class Animal {
  constructor(public name: string) {}
  speak(): string { return `${this.name}이(가) 소리를 냅니다.`; }
}

class Dog extends Animal {
  constructor(name: string, public breed: string) {
    super(name);  // 부모 constructor 호출 필수
  }

  // 오버라이드
  speak(): string { return `${this.name}이(가) 멍멍 짖습니다!`; }

  fetch(): string { return `${this.name}이(가) 공을 가져옵니다.`; }
}

4. 추상 클래스 (abstract)

typescript
abstract class Shape {
  abstract area(): number;
  abstract perimeter(): number;

  describe(): string {
    return `넓이: ${this.area()}, 둘레: ${this.perimeter()}`;
  }
}

class Circle extends Shape {
  constructor(private radius: number) { super(); }

  area(): number { return Math.PI * this.radius ** 2; }
  perimeter(): number { return 2 * Math.PI * this.radius; }
}

// new Shape();      // 오류: 추상 클래스
const circle = new Circle(5);

5. 인터페이스 구현 (implements)

typescript
interface Flyable {
  fly(): string;
  maxAltitude: number;
}

interface Swimmable {
  swim(): string;
}

class Duck implements Flyable, Swimmable {
  maxAltitude = 100;
  fly(): string  { return '오리가 납니다!'; }
  swim(): string { return '오리가 헤엄칩니다!'; }
}
예제 코드 / 강의 자료

전체 강의 자료와 예제 코드는 GitHub에서 자유롭게 받아볼 수 있습니다.

GitHub에서 보기 ↗