타입스크립트 추상 클래스 예제
타입스크립트( Typescript )의 추상 클래스는 abstract class로 선언하는 클래스이다.
추상 클래스는 new를 사용해 직접 인스턴스를 만들 수 없으며, 다른 클래스가 extends로 상속해서 사용한다.
추상 클래스 안에는 구현이 없는 추상 메서드뿐 아니라 실제 코드가 작성된 일반 메서드도 함께 넣을 수 있다.
공통 기능은 부모 클래스에서 구현하고, 클래스마다 달라져야 하는 기능은 추상 메서드로 정의할 수 있다.
⊙
abstract class Animal {
move(): void {
console.log("동물이 움직인다.");
}
}
class Dog extends Animal {}
const dog = new Dog();
dog.move();⊙
abstract class Animal {
abstract makeSound(): void;
}
class Dog extends Animal {
makeSound(): void {
console.log("멍멍");
}
}
const dog = new Dog();
dog.makeSound();
⊙
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log("앞으로 이동한다.");
}
}
class Cat extends Animal {
makeSound(): void {
console.log("야옹");
}
}
const cat = new Cat();
cat.makeSound();
cat.move();
⊙
abstract class Animal {
abstract makeSound(): void;
}
const animal = new Animal();
⊙
class Dog extends Animal {
makeSound(): void {
console.log("멍멍");
}
}
const dog = new Dog();
dog.makeSound();
댓글
댓글 쓰기