자바스크립트 클래스에서 상속을 통해 메서드를 추가적으로 정의하는 방법은 무엇인가요?
예를 들어, 다음은 Animal
클래스를 상속받아 Dog
클래스에서 추가적인 메서드를 정의하는 예시입니다:
class Animal {
constructor(name) {
this.name = name;
}
eat() {
console.log(`${this.name} is eating.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
bark() {
console.log(`${this.name} is barking.`);
}
}
위의 코드에서 Dog
클래스는 Animal
클래스를 상속받아 bark()
메서드를 추가적으로 정의합니다. Dog
클래스는 Animal
클래스의 모든 속성과 메서드를 상속받기 때문에 eat()
메서드도 사용할 수 있습니다.
사용 예시:
const myDog = new Dog("Max", "Labrador");
myDog.eat(); // "Max is eating."
myDog.bark(); // "Max is barking."
위의 예시를 보면, Dog
클래스에서 eat()
메서드를 직접 정의하지 않았음에도 상속을 통해 Animal
클래스의 eat()
메서드를 사용할 수 있음을 확인할 수 있습니다.
상속을 통해 클래스에 메서드를 추가적으로 정의함으로써 코드의 재사용성을 높이고, 개체 지향 프로그래밍의 철학에 따라 코드를 구조화 할 수 있습니다.
참고 자료:
#javascript #class