자바스크립트에서는 클래스 상속(Inheritance)을 통해 기존 클래스에서 동작과 속성을 상속하고 확장할 수 있습니다. 이는 객체 지향 프로그래밍(OOP)의 핵심 개념 중 하나로, 반복되는 코드를 줄이고 재사용성을 높일 수 있습니다.
기본 클래스 생성
먼저, 기본 클래스를 생성해보겠습니다. 이 예시에서는 동물을 나타내는 Animal
클래스를 만들어보겠습니다.
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}
eat() {
return `${this.name} is eating.`;
}
sleep() {
return `${this.name} is sleeping.`;
}
}
위 코드에서 Animal
클래스는 name
과 age
라는 두 가지 속성을 가지고 있습니다. 그리고 eat
과 sleep
이라는 두 가지 메서드를 정의하였습니다.
클래스 상속
이제, Animal
클래스를 상속하여 새로운 클래스인 Dog
클래스를 만들어보겠습니다. Dog
클래스는 Animal
클래스의 동작과 속성을 모두 상속받게 됩니다.
class Dog extends Animal {
constructor(name, age, breed) {
super(name, age);
this.breed = breed;
}
bark() {
return `${this.name} is barking loudly! Woof woof!`;
}
}
위 코드에서 extends
키워드를 사용하여 Dog
클래스가 Animal
클래스를 상속 받는다는 것을 명시하였습니다. super
키워드는 부모 클래스의 생성자를 호출하여 상속받은 속성을 초기화합니다.
Dog
클래스에는 bark
라는 새로운 메서드가 추가되었는데, 이는 Animal
클래스에는 없는 기능입니다.
클래스 확장
Dog
클래스를 확장하여 Poodle
클래스를 만들어보겠습니다. Poodle
클래스는 Dog
클래스를 상속하고, 새로운 속성과 메서드를 추가로 가지게 됩니다.
class Poodle extends Dog {
constructor(name, age, breed, size) {
super(name, age, breed);
this.size = size;
}
jump() {
return `${this.name} can jump high!`;
}
}
위 코드에서 Poodle
클래스는 Dog
클래스를 상속하므로, Poodle
인스턴스는 Animal
, Dog
클래스의 속성과 메서드들을 모두 사용할 수 있습니다.
Poodle
클래스에는 jump
라는 새로운 메서드와 size
라는 속성이 추가되었습니다.
클래스 사용 예시
이제 클래스들을 사용하여 객체를 생성하고 메서드를 호출해보겠습니다.
const animal = new Animal("Animal", 5);
console.log(animal.eat());
console.log(animal.sleep());
const dog = new Dog("Spot", 3, "Labrador");
console.log(dog.eat());
console.log(dog.sleep());
console.log(dog.bark());
const poodle = new Poodle("Fluffy", 2, "Poodle", "Small");
console.log(poodle.eat());
console.log(poodle.sleep());
console.log(poodle.bark());
console.log(poodle.jump());
위 코드의 실행 결과는 다음과 같습니다.
Animal is eating.
Animal is sleeping.
Spot is eating.
Spot is sleeping.
Spot is barking loudly! Woof woof!
Fluffy is eating.
Fluffy is sleeping.
Fluffy is barking loudly! Woof woof!
Fluffy can jump high!
상속과 확장을 통해 클래스를 사용하면 코드의 재사용성과 유지보수성이 향상됩니다. 클래스 상속 및 확장을 이용하여 객체 지향 프로그래밍의 장점을 최대한 활용해보세요!