Menu
Coddy logo textTech

속성과 메서드 상속하기

Coddy JavaScript 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 56개 중 28번째.

클래스가 다른 클래스를 상속(extends)할 때, 부모 클래스의 모든 속성과 메서드를 상속받습니다. 이는 자식 클래스가 부모 클래스에 정의된 모든 것에 자동으로 접근할 수 있음을 의미합니다.

속성과 메서드를 가진 부모 클래스를 만들어 보겠습니다:

class Animal {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  eat() {
    return `${this.name} is eating`;
  }
  
  sleep() {
    return `${this.name} is sleeping`;
  }
}

이제 Animal 클래스를 상속받는 자식 클래스를 만들어 보겠습니다:

class Dog extends Animal {
  constructor(name, age, breed) {
    super(name, age);
    this.breed = breed;
  }
}

Dog 클래스의 인스턴스를 생성합니다:

const rex = new Dog("Rex", 3, "German Shepherd");

이제, Dog 클래스에서 eat()sleep()을 정의하지 않았음에도 불구하고, 우리는 여전히 이 메서드들을 사용할 수 있습니다:

console.log(rex.eat());  // 출력: Rex is eating
console.log(rex.sleep()); // 출력: Rex is sleeping

그리고 모든 상속된 속성에 접근할 수 있습니다:

console.log(rex.name);  // 출력: Rex
console.log(rex.age);   // 출력: 3
console.log(rex.breed); // 출력: German Shepherd
challenge icon

챌린지

Dessert를 상속받는 Cake 클래스를 생성하고 내보내세요. Cake 클래스는 다음을 포함해야 합니다:

  • Dessert로부터 상속받은 모든 속성과 메서드
  • 새로운 속성 flavor
  • 문자열 “Added candles to ${this.name}!”을 반환하는 새로운 메서드 addCandles()

치트 시트

자식 클래스는 extends 키워드를 사용하여 부모 클래스의 모든 속성과 메서드를 상속받습니다:

class Animal {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  eat() {
    return `${this.name} is eating`;
  }
  
  sleep() {
    return `${this.name} is sleeping`;
  }
}

class Dog extends Animal {
  constructor(name, age, breed) {
    super(name, age);
    this.breed = breed;
  }
}

const rex = new Dog("Rex", 3, "German Shepherd");
console.log(rex.eat());  // Rex is eating
console.log(rex.name);   // Rex
console.log(rex.breed);  // German Shepherd

자식 클래스는 상속받은 모든 속성과 메서드를 다시 정의하지 않고도 접근할 수 있습니다.

직접 해보기

import { Dessert } from './desserts.js';
import { Cake } from './desserts.js';

// 테스트 코드 - 수정하지 마세요
const myCake = new Cake("Birthday Cake", 300, "Chocolate");
console.log(myCake.describe());   // "Birthday Cake has 300 calories"가 출력되어야 함
console.log(myCake.flavor);       // "Chocolate"이 출력되어야 함
console.log(myCake.addCandles()); // "Added candles to Birthday Cake!"이 출력되어야 함
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨