TypeScript의 protected 수정자

비공개 속성과 메서드는 자식 클래스에 의해 상속되지 않습니다. 그러나 때로는 속성이나 메서드가 외부에서 접근할 수 없도록 하면서 자식 클래스에게 상속되도록 해야 할 때가 있습니다. 이러한 경우에는 protected 수정자를 사용해야 합니다.

실습을 통해 알아보겠습니다. 우리 클래스 User에 protected 수정자를 사용하여 보호된 메서드 cape를 선언해 보겠습니다:

typescriptclass User {
  protected cape(str: string) {
    return str[0].toUpperCase() + str.slice(1);
  }
}

User 클래스를 상속하는 Student 클래스를 만들어 보겠습니다:

typescriptclass Student extends User {
  private name: string;
  
  constructor(name: string) {
    super();
    this.name = name;
  }
}

이름을 출력하는 메서드를 추가해 보겠습니다:

typescriptclass Student extends User {
  private name: string;
  
  constructor(name: string) {
    super();
    this.name = name;
  }
  
  public showName(): string {
    return this.name;
  }
}

이제 자식 클래스의 메서드 내부에서 부모 클래스의 보호된 메서드를 사용해 보겠습니다:

typescriptclass Student extends User {
  private name: string;
  
  constructor(name: string) {
    super();
    this.name = name;
  }
  
  public showName(): string {
    return this.cape(this.name); // 부모 클래스의 메서드를 사용합니다
  }
}

클래스의 객체를 생성해 보겠습니다:

typescriptlet student: Student = new Student('john');

학생을 출력하기 위해 메서드를 사용해 보겠습니다:

typescriptconsole.log(student.showName());

그러나 클래스 외부에서 cape 메서드를 호출하려는 시도는 오류를 발생시킬 것입니다:

typescriptconsole.log(student.cape('test')); // 오류
Задание 1

다음 클래스가 주어졌습니다:

typescriptclass User {
  protected name: string;
  protected surn: string;
  
  constructor(name: string, surn: string) {
    this.name = name;
    this.surn = surn;
  }
}

이 클래스에서 Employee 클래스를 상속받으세요. Employee 클래스는 보호된 속성 salary를 추가하고, 자신의 속성과 상속받은 속성 모두에 대한 게터를 제공해야 합니다.