C.W.K.
Stream
Lesson 03 of 06 · published

Abstract Class 와 Method

~8 min · classes, abstract, inheritance

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"Abstract 가 '나 쓰려면 extend 해야 함' 말하는 class."

`abstract` 가 뭐 함

abstract class Base { ... } 가 직접 instantiate 못 하는 class 선언. new Base() 가 compile 에러 — 먼저 extend 해야. Abstract class 가 template: 공유 구조와 부분 구현 묘사, 구체는 subclass 에 남김.

Abstract class 가 abstract method(): T 선언 가능 — body 없는 method signature. 구체 subclass 가 구현해야 함. Compile 시점에 강제되는 '이건 너가 제공해야 할 method' 의 type-system 버전.

Abstract 손 뻗을 때

Abstract class 가 자기 몫 할 때:

  • 타입 family 가로질러 공유 state 와 행동 있을 때.
  • Subclass 가 특정 method 구현해야 하는데 나머지 대부분 재사용.
  • Base 의 직접 instantiation 금지하고 싶을 때.

Contract 만 필요하면 (공유 state 없음, 공유 구현 없음), `interface` 써 — 더 가벼움. Abstract class 는 interface 만으론 부족할 때용.

Abstract vs interface

둘 다 contract 묘사. Abstract class 가 구현도 제공. 경험 법칙: 코드 공유 필요하면 abstract. 모양만 공유 필요하면 interface. 많은 codebase 가 둘 다 써 — interface 가 contract 묘사, abstract class 가 그 contract 의 공통 행동 구현.

Abstract 가 '이건 contract' 와 '이건 부분-빌드된 class' 의 선. 아껴서 써 — TypeScript 의 대부분 contract 가 interface 에 살아. Contract 가 공유 구현도 포함할 때 abstract 손 뻗어.

Code

구체 + abstract 멤버 섞인 abstract class·typescript
abstract class Shape {
  // 구체 공유 필드.
  color: string;

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

  // 구체 공유 method.
  describe(): string {
    return `A ${this.color} ${this.kind}`;
  }

  // Abstract — subclass 가 구현해야.
  abstract get kind(): string;
  abstract area(): number;
}

// new Shape('red')  // ❌ Cannot create an instance of an abstract class

class Circle extends Shape {
  radius: number;

  constructor(color: string, radius: number) {
    super(color);
    this.radius = radius;
  }

  get kind(): string { return 'circle' }
  area(): number { return Math.PI * this.radius ** 2 }
}

const c = new Circle('red', 10);
c.describe();     // 'A red circle'
c.area();         // ~314.15...

External links

Exercise

Abstract _pull(): T 호출하는 구체 read(): T method 가진 abstract class Stream<T> 써. 2 구체 subclass 구현: StaticStream (고정 값 반환) 과 RandomStream (랜덤 반환). new Stream() 못 하는지 확인.
Hint
Base 가 read-and-do-extra logic 제공; subclass 가 값 source 제공. 패턴이 stream library 에 흔함 — read() 가 template, _pull() 이 variation point.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.