클래스 상속(Class Extends)

class Whale {
  constructor(
    protected name: string, // 중복 필드
    protected residence: string // 중복 필드
  ) {}

  // 중복 메소드
  public breath(): void {
    console.log(`${this.name}이/가 폐호흡합니다.`);
  }

  public swimming(): void {
    console.log(`${this.name}이/가 헤엄칩니다.`);
  }
}

class FlyingSquirrel {
  constructor(
    protected name: string, // 중복 필드
    protected residence: string // 중복 필드
  ) {}

  // 중복 메소드
  public breath(): void {
    console.log(`${this.name}이/가 폐호흡합니다.`);
  }

  public flying(): void {
    console.log(`${this.name}이/가 날아갑니다.`);
  }
}

// -------------------------- 아래처럼 추상화 가능 --------------------------
class Mammal {
  constructor(
    protected name: string,
    protected residence: string
  ) {}

  public breath(): void {
    console.log(`${this.name}이/가 폐호흡합니다.`);
  }
}

class Whale extends Mammal {
  public swimming(): void {
    console.log(`${this.name}이/가 헤엄칩니다.`);
  }
}

class FlyingSquirrel extends Mammal {
  public flying(): void {
    console.log(`${this.name}이/가 날아갑니다.`);
  }
}

상속 관계에서의 생성자

super 키워드

class Mammal {
  public name: string = '포유류';

  public breath(): void {
    console.log(`${this.name}이/가 폐호흡합니다.`);
  }

}

class Whale extends Mammal {
  public name: string = '고래';

  override breath(): void {
    console.log(`고래고래고래~`);
  }

  public printNames(): void {
    const name: string = '프린트 메소드';
    super.breath(); // Mammal의 breath() 호출
    this.breath(); // Whale의 breath() 호출

    console.log(name);        // printNames()의 지역 변수 name
    console.log(this.name);   // Whale의 인스턴스 변수 name
    console.log(super.name);  // Error: Class field 'name' defined by the parent class is not accessible in the child class via super.
  }
}

const whale = new Whale();
whale.printNames();

오버라이딩(Overriding)