본문 바로가기

TypeScript

[TypeScript] 추상 클래스

추상 클래스

 

추상 클래스는 클래스와는 다르게 인스턴스화를 할 수 없는 클래스

 

추상 클래스의 목적

 

- 상속을 통해 자식 클래스에서 메서드를 제각각 구현하도록 강제를 하는 용도

- 물론 추상 클래스도 최소한의 기본 메서드는 정의할 수 있음.

- 핵심기능의 구현은 전부 자식클래스에게 위임을 하는 것

 

추상클래스 사용방법

 

- 추상 클래스 및 추상함수는 abstract 키워들 사용

- 추상 클래스는 1개이상의 추상함수가 있는 것이 일반적

 

abstract class Shape {
  abstract getArea(): number; // 추상 함수 정의!!!

  printArea() {
    console.log(`도형 넓이: ${this.getArea()}`);
  }
}

class Circle extends Shape {
  radius: number;

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

  getArea(): number { // 원의 넓이를 구하는 공식은 파이 X 반지름 X 반지름
    return Math.PI * this.radius * this.radius;
  }
}

class Rectangle extends Shape {
  width: number;
  height: number;

  constructor(width: number, height: number) {
    super();
    this.width = width;
    this.height = height;
  }

  getArea(): number { // 사각형의 넓이를 구하는 공식은 가로 X 세로
    return this.width * this.height;
  }
}

const circle = new Circle(5);
circle.printArea();

const rectangle = new Rectangle(4, 6);
rectangle.printArea();

위의 Shape 클래스의 abstract getArea(): number; 이 부분이 추상 함수이다. 이 추상 클래스를 상속 받은 자식 클래스들은 반드시 getArea 함수를 구현해야 함.

 

 

 

'TypeScript' 카테고리의 다른 글

[TypeScript] 객체 지향 설계원칙 - S.O.L.I.D  (0) 2023.07.26
[TypeScript] 인터페이스  (0) 2023.07.26
[TypeScript] 상속  (0) 2023.07.26
[TypeScript] 클래스  (0) 2023.07.26
[TypeScript] 프로젝트 세팅  (0) 2023.07.26