TypeScript

[TypeScript]클래스 상속(Class Inheritance)

DevStory 2022. 3. 20.

클래스 상속(Class Inheritance)이란?

상속이란 현실 세계에서 부모가 자식에게 재산을 물려주듯이 프로그래밍에서는 부모 클래스가 자식 클래스에게 필드 또는 메서드를 물려주는 개념입니다.

 

메서드와 필드를 자식에게 물려주는 클래스를 기본, 상위 또는 슈퍼 클래스라고 말하며, 부모 클래스의 필드 및 메서드를 상속받는 클래스를 서브 또는 자식 클래스라고 합니다.

 

예를 들어 몬스터(Monster), 인간형(Human), 동물형(Animal)이라는 3가지 클래스가 존재합니다.

class Monster {
}

class Human {
}

class Animal {
}

위 세 가지 클래스는 캐릭터를 공격하므로 Attack()이라는 함수를 가집니다.

class Monster {
  Attack() {
    console.log("Attack");
  }
}

class Human {
  Attack() {
    console.log("Attack");
  }
}

class Animal {
  Attack() {
    console.log("Attack");
  }
}

동일한 함수를 클래스마다 정의하다 보니 코드가 비효율적이고 길어진다는 문제가 발생합니다. HumanAnimalMonster에서 파생되므로 Monster 클래스만 Attack() 함수를 가지고 HumanAnimal 클래스를 상속하기 위해 extends 키워드를 사용합니다.

class Monster {
  Attack() {
    console.log("Attack");
  }
}

class Human extends Monster {
}

class Animal extends Monster {
}

var knight = new Human();
var dog = new Animal();

knight.Attack();
// Attack
dog.Attack();
// Attack

위 예제 코드는 Monster 클래스를 상속받는 두 개의 자식 클래스인 HumanAnimal 클래스를 만들었습니다. Human 클래스의 객체인 knight, Animal 클래스의 객체인 dog에서 부모 클래스의 Attack() 함수를 호출했습니다.

 

위 예제처럼 클래스 상속을 사용한다면 공통된 함수를 여러 번 정의하지 않고 한 번만 정의할 수 있습니다.

반응형

super 함수로 생성자 기능을 상속

이번에는 super()라는 함수로 부모 클래스의 생성자를 사용하는 방법입니다. 게임에서 몬스터마다 체력(HP)가 존재하므로 부모 클래스 Monster에 number 타입의 hp라는 필드를 정의합니다.

 

그리고 Human 클래스는 성별을 표현하는 string 타입의 gender 필드를 정의하고 동물은 포유류인지 파충류인지 분류하기 위해 string 타입의 animalType 필드를 정의합니다.

class Monster {
  hp:number;
  constructor(hp) {
    this.hp = hp;
  }
  Attack() {
    console.log("Attack");
  }
}

class Human extends Monster {
  gender:string;
  constructor(gender) {
    this.gender = gender;
  }
}

class Animal extends Monster {
  animaltype:string;
  constructor(animaltype) {
    this.animaltype = animaltype;
  }
}

var knight = new Human("남자");
var dog = new Animal("파충류");

위 예제는 다음 사진처럼 자식 클래스의 생성자(constructor)에서 컴파일 오류가 발생합니다.

이러한 컴파일 오류는 부모 클래스와 자식 클래스에 생성자가 존재하는 경우 발생하는데, 자식 클래스의 생성자에서 this를 사용하기 위해서는 super() 함수를 반드시 호출해야 합니다.

 

new 연산자를 사용하여 클래스 객체를 생성하면 객체를 this에 할당하는데, 상속받은 클래스는 객체를 this에 할당하는 작업을 부모 생성자에서 처리하므로 부모 생성자를 실행하는 super() 함수를 호출해야 합니다. 

오류를 해결하기 위해 자식 클래스의 생성자에서 super() 함수를 추가하고 다음 예제처럼 자식 클래스의 생성자를 수정합니다.

class Monster {
  hp:number;
  constructor(hp:number) {
    this.hp = hp;
  }
  Attack() {
    console.log("Attack");
  }
}

class Human extends Monster {
  gender:string;
  constructor(hp:number, gender:string) {
    super(hp);
    this.gender = gender;
  }
}

class Animal extends Monster {
  animaltype:string;
  constructor(hp:number, animaltype:string) {
    super(hp);
    this.animaltype = animaltype;
  }
}

var knight = new Human(100, "남자");
var dog = new Animal(150, "파충류");

부모 클래스의 생성자에는 매개변수가 존재하므로 부모 생성자를 호출하는 super()에도 매개변수가 필요합니다. 자식 클래스의 생성자에서 부모 클래스의 생성자를 호출하기 위해 필요한 매개변수를 전달합니다.


정리

이번 포스팅은 클래스 상속에 대해 소개하였습니다.

  • 클래스 상속하기 위해서는 extends 키워드를 사용합니다.
  • 부모 클래스의 생성자를 호출하기 위해서는 자식 클래스의 생성자에서 super()를 호출합니다.
  • 부모 클래스와 자식 클래스에 생성자가 존재하고 자식 클래스의 생성자에서 this를 사용하기 위해서는 super()를 먼저 호출하고 this를 사용합니다.
반응형

댓글