저장을 습관화

객체 지향 프로그래밍 - 추상 클래스 본문

공부/TypeScript

객체 지향 프로그래밍 - 추상 클래스

ctrs 2023. 8. 1. 22:15

1. 추상 클래스란 

추상 클래스는 일반적인 클래스와는 다르게 인스턴스화를 할 수 없다.(붕어빵의 틀로써 사용할 수 없다.)

 

2. 추상 클래스의 존재 이유

이러한 추상 클래스의 목적은 상속을 통해 자식 클래스에서 메서드를 제각각 구현하도록 강제하기 위해서이다.

최소한의 기본 메서드까지는 정의 해주지만, 핵심 기능의 구현은 자식 클래스에게 위임한다.

 

3. 추상 클래스 사용 방법

추상 클래스 및 추상 함수는 abstract 키워드를 사용하여 정의하며,

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

 

사용 예시)

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

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

class Circle extends Shape {  // 자식 클래스 1
  radius: number;

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

  getArea(): number {  // 추상 함수는 반드시 가져와야 한다. 없다면 에러 발생, 하단 참조
    // 원의 넓이를 구하는 공식은 파이 X 반지름 X 반지름
    return Math.PI * this.radius * this.radius;
  }
}

class Rectangle extends Shape {  // 자식 클래스 2
  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(); // 78.5398163397

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

 

추상 클래스로부터 상속 받아온 클래스는 추상 함수를 반드시 사용하여야 하는데

사용하지 않을 경우 아래와 같은 에러가 발생한다.

non-abstract class 'Circle' does not implement all abstract members of 'Shape'
비-추상 클래스 'Circle'은 'Shape'의 모든 추상 멤버를 구현하지 않습니다.