추상 클래스(Abstract Class)란?
- 스스로는 객체를 생성할 수 없는 미완성된 설계도
- 오직 자식 클래스에게 상속(extends)되어 공통된 기능을 물려주거나, 특정 기능을 구현하도록 강제하기 위해 존재
- 아래 페이지 참조
추상 클래스(Abstract Class) 예시
- 클래스 앞에
abstract 키워드를 붙여 추상 클래스 정의
- 하나 이상의 추상메소드(Abstract Method)를 포함
- 추상메소드(Abstract Method)는 반드시 자식 클래스에서 오버라이딩해야만 하는 메소드
abstract class Mammal {
constructor(
protected name: string,
protected residence: string
) {}
// 일반 메소드 : 모든 자식이 공통으로 사용할 기능 (오버라이딩이 비필수)
public breath(): void {
console.log(`${this.name}이/가 폐호흡합니다.`);
}
// 추상 메소드 : 자식쪽에서 무조건 오버라이딩 하도록 강제
abstract printResidence(): void;
}
class Whale extends Mammal {
constructor(name: string, residence: string) {
super(name, residence);
}
// 추상 메소드를 오버라이딩하여 구현 (필수)
override printResidence(): void {
console.log(`${this.residence}에 삽니다.`);
}
}
// 해당 클래스는 추상 메소드를 구현하지 않았으므로 에러 발생
// Error: Non-abstract class 'FlyingSquirrel' does not implement inherited abstract member printResidence from class 'Mammal'.
class FlyingSquirrel extends Mammal {
constructor(name: string, residence: string) {
super(name, residence);
}
}