JavaScript Inheritance


자바스크립트에서 상속과 서브클래스(Subclass)는 객체 지향 프로그래밍의 중요한 개념입니다. ES6에서는 클래스 문법이 도입되어 상속과 서브클래스를 보다 간결하고 직관적으로 구현할 수 있게 되었습니다. 이 글에서는 자바스크립트에서 상속과 서브클래스를 사용하는 방법에 대해 상세히 설명하겠습니다.

1. 상속의 기본 개념

상속(Inheritance)은 한 클래스(부모 클래스 또는 슈퍼클래스)의 속성과 메서드를 다른 클래스(자식 클래스 또는 서브클래스)가 물려받아 사용할 수 있게 하는 것입니다. 이를 통해 코드의 재사용성을 높이고, 코드의 중복을 줄일 수 있습니다.

2. ES6 클래스에서의 상속

ES6에서는 classextends 키워드를 사용하여 클래스를 정의하고 상속을 구현할 수 있습니다. 자식 클래스는 부모 클래스의 모든 속성과 메서드를 상속받습니다.

2.1 부모 클래스 정의

먼저 부모 클래스를 정의합니다.

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

2.2 자식 클래스 정의

이제 extends 키워드를 사용하여 자식 클래스를 정의합니다.

class Dog extends Animal {
  constructor(name, breed) {
    super(name); // 부모 클래스의 생성자 호출
    this.breed = breed;
  }

  bark() {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog('Rex', 'German Shepherd');
dog.speak(); // Rex makes a sound.
dog.bark();  // Rex barks.
  • extends 키워드를 사용하여 Dog 클래스가 Animal 클래스를 상속받습니다.
  • 자식 클래스의 생성자에서 super 키워드를 사용하여 부모 클래스의 생성자를 호출해야 합니다. 이는 자식 클래스의 this 키워드를 사용하기 전에 반드시 호출해야 합니다.

3. 메서드 오버라이딩

자식 클래스는 부모 클래스의 메서드를 재정의(오버라이딩)할 수 있습니다. 오버라이딩된 메서드는 자식 클래스의 인스턴스에서 호출됩니다.

class Cat extends Animal {
  constructor(name) {
    super(name);
  }

  speak() {
    console.log(`${this.name} meows.`);
  }
}

const cat = new Cat('Whiskers');
cat.speak(); // Whiskers meows.
  • Cat 클래스에서 speak 메서드를 오버라이딩하여 고유의 동작을 정의합니다.
  • 부모 클래스의 speak 메서드는 자식 클래스에서 호출되지 않습니다.

4. 정적 메서드 상속

정적 메서드도 상속될 수 있으며, 자식 클래스에서 호출할 수 있습니다.

class Vehicle {
  static identify() {
    console.log('This is a vehicle.');
  }
}

class Car extends Vehicle {}

Car.identify(); // This is a vehicle.
  • Car 클래스는 Vehicle 클래스의 정적 메서드 identify를 상속받습니다.

5. 서브클래스의 정적 메서드와 속성

자식 클래스는 고유의 정적 메서드와 속성을 가질 수 있습니다.

class Person {
  static species = 'Homo sapiens';

  static greet() {
    console.log('Hello, human!');
  }
}

class Teacher extends Person {
  static school = 'High School';

  static teach() {
    console.log('Teaching students...');
  }
}

console.log(Teacher.species); // Homo sapiens
console.log(Teacher.school);  // High School
Teacher.greet(); // Hello, human!
Teacher.teach(); // Teaching students...
  • Teacher 클래스는 Person 클래스의 정적 속성 species와 정적 메서드 greet를 상속받으며, 고유의 정적 속성 school과 정적 메서드 teach를 정의합니다.

6. 다중 상속과 믹스인

자바스크립트는 클래스 기반 다중 상속을 직접 지원하지 않지만, 믹스인(Mixin) 패턴을 사용하여 여러 클래스의 기능을 결합할 수 있습니다.

const CanWalk = {
  walk() {
    console.log(`${this.name} is walking.`);
  }
};

const CanSwim = {
  swim() {
    console.log(`${this.name} is swimming.`);
  }
};

class Creature {
  constructor(name) {
    this.name = name;
  }
}

class Amphibian extends Creature {
  constructor(name) {
    super(name);
    Object.assign(this, CanWalk, CanSwim);
  }
}

const frog = new Amphibian('Froggy');
frog.walk(); // Froggy is walking.
frog.swim(); // Froggy is swimming.
  • Object.assign을 사용하여 여러 믹스인 객체의 메서드를 자식 클래스 인스턴스에 결합합니다.

7. 상속과 접근 제어

자바스크립트 클래스에서는 public, private, protected와 같은 접근 제어자를 사용하여 속성 및 메서드의 접근 범위를 지정할 수 없습니다. 하지만, ES2022에서 도입된 #을 사용한 Private 필드를 통해 클래스 외부에서의 접근을 제어할 수 있습니다.

class Account {
  #balance;

  constructor(initialBalance) {
    this.#balance = initialBalance;
  }

  getBalance() {
    return this.#balance;
  }

  deposit(amount) {
    this.#balance += amount;
  }
}

const account = new Account(1000);
console.log(account.getBalance()); // 1000
account.deposit(500);
console.log(account.getBalance()); // 1500
console.log(account.#balance); // SyntaxError: Private field '#balance' must be declared in an enclosing class
  • #balance는 Private 필드로 클래스 외부에서 접근할 수 없습니다.

8. 서브클래스의 생성자와 초기화

서브클래스의 생성자는 부모 클래스의 생성자를 호출하여 상속받은 속성을 초기화할 수 있습니다. 이때 super 키워드를 사용합니다.

class Employee {
  constructor(name, position) {
    this.name = name;
    this.position = position;
  }
}

class Manager extends Employee {
  constructor(name, position, department) {
    super(name, position); // 부모 클래스의 생성자 호출
    this.department = department;
  }

  displayInfo() {
    console.log(`${this.name} is a ${this.position} in the ${this.department} department.`);
  }
}

const manager = new Manager('Alice', 'Manager', 'Sales');
manager.displayInfo(); // Alice is a Manager in the Sales department.
  • super 키워드는 자식 클래스의 생성자에서 부모 클래스의 생성자를 호출합니다.

결론

자바스크립트의 ES6 클래스는 상속과 서브클래스를 구현하는 데 있어 강력하고 직관적인 문법을 제공합니다. 이를 통해 코드 재사용성을 높이고, 유지보수를 용이하게 할 수 있습니다. 상속을 통해 부모 클래스의 속성과 메서드를 물려받아 자식 클래스에서 새로운 기능을 추가하거나 기존 기능을 재정의할 수 있습니다. 믹스인 패턴을 사용하면 다중 상속의 효과를 구현할 수 있으며, Private 필드를 통해 접근 제어를 보다 엄격하게 관리할 수 있습니다.

요약

  1. 상속: extends 키워드를 사용하여 자식 클래스가 부모 클래스를 상속받습니다.
  2. 메서드 오버라이딩: 자식 클래스에서 부모 클래스의 메서드를 재정의할 수 있습니다.
  3. 정적 메서드와 속성: 정적 메서드와 속성도 상속됩니다.
  4. 다중 상속과 믹스인: 믹스인 패턴을 사용하여 여러 클래스를 결합할 수 있습니다.
  5. Private 필드: # 키워드를 사용하여 Private 필드를 정의하고 접근을 제한할 수 있습니다.
  6. 생성자와 초기화: super 키워드를 사용하여 부모 클래스의 생성자를 호출하고 초기화할 수 있습니다.

이러한 개념들을 활용하면 자바스크립트에서 더욱 강력하고 유연한 객체 지향 프로그래밍을 구현할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *