추상화 클래스라는 개념은 대부분 객체 지향 프로그래밍을 다루는 언어에서 존재하는 개념이다.
이 개념을 한 마디로 정리하자면 인스턴스화를 하지 못하게 막는 것이다.
abstract class ModelWithId {
id: number;
constructor(id: number) {
this.id = id;
}
}
추상화 클래스는 class 앞에 abstract 키워드를 붙여주면 된다. 이렇게 하면 new 키워드로 ModelWithId의 인스턴스를 생성할 수 없게 된다.
const modelWithId = new ModelWithId(123); // error
그렇다면 굳이 만들어 놓은 클래스를 인스턴스화 하지 못하게 막는 걸까?
일반적으로 인스턴스화 할 필요 없는 클래스인데 다른 클래스에서 상속을 받거나 혹은 공유되는 프로퍼티나 메소드를 정의하고 싶을 때 사용하기 위함이다.
예제를 살펴보자.
abstract class ModelWithId {
id: number;
constructor(id: number) {
this.id = id;
}
}
class Product extends ModelWithId {}
const product = new Product(1);
console.log(product.id); // 1
클래스뿐만 아니라 메소드도 추상화할 수 있다.
abstract class ModelWithAbstractMethod {
abstract shout(): string;
}
class Person extends ModelWithAbstractMethod {
shout(): string {
return '소리 질러';
}
}
추상화 메소드를 정의하면 상속받은 클래스의 메소의 구조를 강제할 수 있다는 특징이 있다.