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 Animal {
constructor() {
console.log("동물");
}
}
class Mammal extends Animal {
constructor() {
super(); // 부모 생성자 호출 (생략 불가)
console.log("포유류");
}
}
class Whale extends Mammal {
constructor() {
super(); // 부모 생성자 호출 (생략 불가)
console.log("고래");
}
}
// 결과: 동물 -> 포유류 -> 고래 순으로 출력
const whaleInstance = new Whale();
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();
부모에게 상속받은 메소드를 자식이 재정의 하여 사용 하는 것
override 키워드를 메소드명 앞에 붙여 오버라이딩을 한다는 것을 명시 (v4.3+)
오버라이딩은 아래의 조건을 만족해야 한다.
class Mammal {
constructor(
protected name: string,
protected residence: string
) {}
public breath(): void {
console.log(`${this.name}이/가 폐호흡합니다.`);
}
public move(): void {
console.log(`${this.name}이/가 이동합니다.`);
}
}
class Whale extends Mammal {
// 오버라이딩: 부모의 breath를 무시하고 새로 정의함
override breath(): void {
console.log(`고래고래고래~`);
}
// 오버라이딩: 부모의 기능도 같이 쓰고 싶을 때
override move(): void {
super.breath(); // 부모의 breath 호출
console.log(`${this.name}이/가 이동합니다.`);
}
}