1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

アクセス修飾子

Last updated at Posted at 2022-07-07

アクセス修飾子とは

プロパティやメソッドに対して、アクセスレベルを設定できる
public/protected/private がある

クラスを定義

動物のクラスがあり、インスタンス化している

class Animal {
  age: number = 10;
  isCry: boolean = false;

  constructor(isCry: boolean) {
    this.isCry = isCry;
  }
  cry(): void {
    if (this.isCry) {
      console.log(`age:${this.age}`);
    }
  }
}

let dog = new Animal(true);
dog.cry();

public

public はどこからでもアクセスできる
デフォルトは public になっている

class Animal {
  public age: number;
  sex: string;
}

let dog = new Animal();
dog.age = 12;
dog.sex = 'オス';

自身のプロパティとして、自動的に取り込むことができる
なので初期化の必要なし

class Animal {
  age: number = 10;

  constructor(public isCry: boolean) {}
  cry(): void {
    if (this.isCry) {
      console.log(`age:${this.age}`);
    }
  }
}

let dog = new Animal(true);
dog.cry();

protected

自身とその派生クラスの中でアクセスできる

class Animal {
  public age: number;
  sex: string;
  protected sayAge() {
    console.log(`${this.age}才`);
  }
}

let dog = new Animal();
dog.age = 12;
dog.sex = 'オス';
//エラー
dog.sayAge;

サブクラスの中なら使える

class Animal {
  public age: number;
  sex: string;
  protected sayAge() {
    console.log(`${this.age}才`);
  }
}

let dog = new Animal();
dog.age = 12;
dog.sex = 'オス';

class BigAnimal extends Animal {
  constructor(age: number) {
    super();
    this.age = age;
    this.sayAge();
  }
}

let gorilla = new BigAnimal(20);

private は自身のクラスのみ

class Animal {
  public age: number;
  sex: string;
  private sayAge() {
    console.log(`${this.age}才`);
  }
}

let dog = new Animal();
dog.age = 12;
dog.sex = 'オス';

class BigAnimal extends Animal {
  constructor(age: number) {
    super();
    this.age = age;
    //エラー
    this.sayAge();
  }
}

let gorilla = new BigAnimal(20);

サブクラスでも使えない

まとめ

アクセスレベル
public > protected > private

public : オール OK
protected : サブクラスまで OK
private : 自身のクラスのみ OK

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?