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クラスを作成してください。 このクラスは、保護されたプロパティsalaryを追加し、 自身のプロパティと継承したプロパティすべてのゲッターを実装する必要があります。