추상 클래스는 보통 파생될 클래스들의 공통점을 모아서 정의하기 위해서 사용됨. 일반적인 클래스와는 다르게 바로 인스턴스화 되지 않음.
추상 클래스를 선언하기 위해서는 아래처럼 abstract 키워드를 사용해야함.
abstract class Employee {
//...
}
일반적으로 추상클래스는 하나 이상의 추상 메소드를 가지고 있음. 추상 메소드는 아무 구현되 되지 않은 메소드로 그냥 형식만 정의해둔거고 메소드의 내용물은 자식 클래스에서 정의해야함.
아래는 getSalary() 추상 메소드를 가진 Employee 추상 클래스임.
abstract class Employee {
constructor(private firstName: string, private lastName: string) {
}
abstract getSalary(): number
get fullName(): string {
return `${this.firstName} ${this.lastName}`;
}
compensationStatement(): string {
return `${this.fullName} makes ${this.getSalary()} a month.`;
}
}
Employee 클래스를 보면
firstName과 lastName property를 선언해둠getSalary() 메소드는 추상 메소드이기 때문에 자식 클래스에서 method body를 정의할거임.getFullName()과 compenstationStatement() 메소드는 추상 메소드가 아니어서 구현이다 되어있음.Employee가 추상 클래스이기 때문에 이거로는 객체를 생성할 수 없음.
let employee = new Employee('John','Doe');
error TS2511: Cannot create an instance of an abstract class.
아래의 FullTimeEmployee 클래스는 Employee클래스를 상속했음. 생성자에 salary property를 추가했고 getSalaray()가 부모 클래스의 추상 메소드이기 때문에 여기서 메소드를 구현해줬음.
class FullTimeEmployee extends Employee {
constructor(firstName: string, lastName: string, private salary: number) {
super(firstName, lastName);
}
getSalary(): number {
return this.salary;
}
}
아래의 Contractor 클래스도 Employee클래스를 상속 했음.
class Contractor extends Employee {
constructor(firstName: string, lastName: string, private rate: number, private hours: number) {
super(firstName, lastName);
}
getSalary(): number {
return this.rate * this.hours;
}
}
다음과 같이 FullTimeEmployee와 Contractor객체를 생성해서 compensationStatement()를 불러오면 잘 나오는것을 확인 가능함.
let john = new FullTimeEmployee('John', 'Doe', 12000);
let jane = new Contractor('Jane', 'Doe', 100, 160);
console.log(john.compensationStatement());
console.log(jane.compensationStatement());
// output
John Doe makes 12000 a month.
Jane Doe makes 16000 a month.
추상 클래스는 바로 인스턴스화 할 수 없음추상 클래스는 최소 하나의추상 메소드를 포함하고 있어야함(문법적으로 강제되는것은 아님)추상 클래스를 사용하기 위해서는추상 클래스를 상속하고 거기서추상 메소드를 구현해야함