클래스 - 상속

Changhan·2025년 2월 4일

Typescript

목록 보기
25/29
class Parent {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  dance() {
    console.log(`parent: ${this.name}이 춤을 춘다`);
  }
}

class Child extends Parent {
  age: number;

  constructor(name: string, age: number) {
    super(name);
    this.age = age;
  }

  sing() {
    console.log(`child: ${this.name}이 노래를 부른다.`);
  }
}

자바스크립트의 클래스의 상속을 다시 살펴보자.

각각의 클래스의 인스턴스를 만들어보자.

const taeyeon = new Parent('태연');
const yuna = new Child('윤아', 32);
taeyeon.dance(); // O
taeyeon.sing(); // X
yuna.dance(); // O
yuna.sing(); // O

Parent 클래스인 taeyeon 인스턴스는 부모 클래스지만 자식 클래스의 메소드인 sing 함수를 호출할 수는 없다.
하지만 부모 클래스(Parent)를 상속받은 Child 클래스는 부모 클래스의 모든 프로퍼티, 메소드를 사용할 수 있다. 따라서 yuna 인스턴스는 부모 클래스의 메소드인 dance 함수를 호출할 수 있다.


이를 이용해 클래스 타입을 이용한 할당 예제를 살펴보자.

let person : Parent;
person = taeyeon; // 1
person = yuna; // 2

1) Parent 클래스인 person 변수에 Parent 클래스인 taeyeon을 할당했다. 이는 어찌보면 당연한 것이다.
2) Parent 클래스인 person 변수에 Child 클래스인 yuna를 할당했다. 이것은 Child 클래스가 Parent 클래스를 상속받았기 때문에 가능하다.

여기서 주의해야 할 점은 2의 반대인 Child 클래스 타입에 Parent 클래스 타입을 할당할 수는 없다는 것이다.

하지만 이를 가능하게 할 수 있다. 바로 optional을 이용하는 것이다.

class Parent2 {
  name: string;

  constructor(name: string) {
    this.name = name;
  }
}

class Child2 extends Parent2 {
  age?: number;

  constructor(name: string, age?: number) {
    super(name);
    this.age = age;
  }
}

const nara = new Parent2('나라');
const ahri = new Child2('아리', 20);

let child: Child2;
child = ahri;
child = nara; 

Child2 에서 age가 없으면 Parent와 구조가 동일해진다. 구조가 동일하면 할당이 가능해지는 것이다.

한 문장으로 정리하자면...

부모 클래스는 자식 클래스에 할당할 수 없고, 부모 클래스를 상속받은 자식클래스는 부모 클래스에 할당이 가능하다.

0개의 댓글