Menu
Coddy logo textTech

깊은 상속의 한계

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

inheritance는 유용하지만, 매우 깊은 inheritance 계층 구조(부모 → 자식 → 손자 → 증손자)를 만들면 문제가 발생할 수 있습니다. 연결 고리가 깊어질수록 코드를 이해하고, 유지 관리하고, 수정하기가 더 어려워집니다.

깊은 inheritance 체인에서 어떤 일이 일어나는지 살펴봅시다:

// 기본 클래스
class Vehicle {
  constructor(type) {
    this.type = type;
    this.isRunning = false;
  }
  
  start() {
    this.isRunning = true;
    console.log(`${this.type} started`);
  }
}

// 상속의 첫 번째 수준
class Car extends Vehicle {
  constructor(make, model) {
    super("Car");
    this.make = make;
    this.model = model;
    this.wheels = 4;
  }
  
  honk() {
    console.log("Beep beep!");
  }
}

// 상속의 두 번째 수준
class SportsCar extends Car {
  constructor(make, model, topSpeed) {
    super(make, model);
    this.topSpeed = topSpeed;
  }
  
  race() {
    this.start();
    console.log(`Racing at ${this.topSpeed} mph!`);
  }
}

이 예제에서 SportsCar는 상속 계층에서 두 단계 아래에 있습니다. 이로 인해 몇 가지 문제가 발생할 수 있습니다:

  1. Vehicle의 변경 사항이 예기치 않게 SportsCar를 손상시킬 수 있습니다
  1. 상속 체인이 길어질수록 메서드와 속성이 어디에서 비롯되었는지 추적하기가 더 어려워집니다
  1. 충분히 유연하지 않을 수 있는 "is-a" 관계를 강요받게 됩니다
challenge icon

챌린지

로봇이 제대로 작동하도록 Robot.js 파일을 완성하세요. 현재 로봇은 만들어져 있지만 아무것도 할 수 없습니다.

<strong>Robot.js</strong>에서 수행할 작업:

  1. 생성: Robot constructor 내부에 speaker와 mover 구성 요소를 만드세요.
  2. 사용: 메서드에서 구성 요소를 사용하세요.
    1. greet()에서: this.speaker.speak("Hello!");을 호출하세요.
    2. walkForward()에서: this.mover.move("forward");를 호출하세요.

이렇게 하는 이유: 이것은 컴포지션입니다. 즉, 로봇은 더 작은 구성 요소들을 결합하여 만들어집니다. 로봇은 이러한 기능을 상속하는 대신, 말하기를 위한 has-a speaker와 이동을 위한 has-a mover를 가집니다.

직접 해보기

import { Robot } from './Robot.js';

const myRobot = new Robot('Robo');

myRobot.greet();     // 출력되어야 함: Saying: "Hello!"
myRobot.walkForward(); // Should output: Moving forward
quiz icon실력 점검

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

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

직접 연습해 보세요: 온라인 JavaScript 컴파일러