Abstraction
객체지향프로그래밍에는 추상 클래스와 구체 클래스가 존재합니다. 구체 클래스는 new 키워드를 통해 생성할 수 있고 추상 클래스는 구체 클래스가 가져야 할 속성을 지정하는 도면이기 때문에 abstract 키워드를 사용해 선언합니다. 다만 이 abstract class는 인스턴스를 자체적으로 생성할 수 없는데요. 만약 추상 클래스에 객체 인스턴스를 생성하는 경우 cannot create an instance of an abstract class 라는 오류를 던질 겁니다.
TypeScript의 추상 클래스
타입스크립트에서 추상클래스의 목적은 구체 클래스 (하위 클래스)의 공통 동작을 묶는 것입니다.
abstarct class Student {
// ...
}
학생마다 나이가 있기 때문에 age라는 필드를 추가합니다.
abstract class Student {
private _age: number;
constructor (studentAge: number) {
this._age = studentAge;
}
get age() {
return this._age;
}
set age(studentAge: number) {
this._age = studentAge;
}
}
이제 구체 클래스인 HighSchool Student와 MiddleSchool Student 클래스를 생성하고 extends로 Student 클래스를 상속받도록 구현해보면
class HighSchoolStudent extends Student {
constructor(theStudentAge: number) {
super(theStudentAge);
}
}
class MiddleSchoolStudent extends Student {
constructor(theStudentAge: number) {
super(theStudentAge);
}
}
두 구체 클래스는 인스턴스를 생성할 수 있는 구체 클래스로 작동합니다.
const highschoolstudents: HighSchoolStudent = new HighSchoolStudent(19);
const middleschoolstudents: MiddleSchoolStudent = new MiddleSchoolStudent(16);
console.log(`HighSchoolStudent Age: ${highschoolstudents.age}`);
// HighSchoolStudent Age: 19
console.log(`MiddleSchoolStudent Age: ${middleschoolstudents.age}`);
// MiddleSchoolStudent Age: 16
메소드도 overwrite 해주어 사용할 수 있습니다. 정리하자면 추상 클래스는 인스턴스를 생성할 수 없으며 추상 클래스는 공통 속성을 정의하는 클래스입니다. 더하여 추상 함수는 추상 클래스 안에 정의해둔 후 구체 클래스에서 구현해 사용 가능합니다.
'Frontend > TypeScript' 카테고리의 다른 글
TypeScript What does "keyof typeof" mean? (0) | 2023.01.18 |
---|---|
TypeScript super vs this & setter/getter (0) | 2023.01.16 |
TypeScript - infer (0) | 2023.01.14 |
TypeScript type vs interface (0) | 2023.01.14 |
TypeScript 전개 연산자(Spread 문법) (0) | 2023.01.13 |