• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

추상클래스를 상속받은 구현클래스에서 private 접근 불가관련 해서 질문 있습니다.

23.07.20 17:14 작성 조회수 182

0

추상 클래스에서 private으로 선언한 것은 추상클래스를 상속받아 구현하는 실제 클래스에서도 접근이 안되고 protected로 바꾸라고 하던데

어짜피 구현은 추상클래스를 상속받은 구현클래스에서 해야하는데 접근 할 수 없다면 추상클래스에서 private가 어떤 역할을 하는건지 모르겠습니다.

// 추상 클래스
abstract class AbstractClass {
  private readonly a: string = "init";
  protected b: number = 1;
  c: string = "기본값이 public";

  abstract method(a: string): void;

  method2() {
    console.log(this.a);
    console.log(this.b);
    console.log(this.c);
  }
}

class realClass extends AbstractClass {
  method(a: string) {
    console.log(this.a); //error
    console.log(this.b);
    console.log(this.c);
  }
}

 

type error msg : TS2341: Property 'a' is private and only accessible within class 'AbstractClass'.

답변 3

·

답변을 작성해보세요.

0

raipendalk님의 프로필

raipendalk

2023.07.28

추상 클래스에서 private 필드를 쓸 일이 있냐고, 대체 어떨 때 쓰길래 필요한건지 물어보신 것 같습니다.

abstract method가 존재할 수 있다는 것만 빼면 abstract class도 class와 동일한 역할을 합니다. 즉, 추상메서드가 아닌 일반 메서드가 존재할 수 있고, 그 메서드에서만 사용하는 변수가 필요하다면 프라이빗으로 쓸 수도 있습니다. 진짜로 쓸모있는 abstract class에서의 private 변수 예시입니다.

abstract class Animal {
    private callCount: number = 0;

    abstract crying(): void;

    call():void{
        this.crying();
        this.callCount++;
        console.log(`저를 ${this.callCount}번째 불러주셨군요?`);
    }

}

class Dog extends Animal{
    crying(){
        console.log("멍멍");
    }
}

class Cat extends Animal{
    crying(){
        console.log("야옹");
    }
}

const main = ():void => {
    const choco: Dog = new Dog();
    const bori: Dog = new Dog();
    const nabi: Cat = new Cat();

    choco.call();   //멍멍 저를 1번째 불러주셨군요
    bori.call();    //멍멍 저를 1번째 불러주셨군요
    choco.call();   //멍멍 저를 2번째 불러주셨군요
    choco.call();   //멍멍 저를 3번째 불러주셨군요
    nabi.call();    //야옹 저를 1번째 불러주셨군요
    nabi.call();    //야옹 저를 2번째 불러주셨군요
    bori.call();    //멍멍 저를 2번째 불러주셨군요
}

main();

위 예제에서 call()은 모든 Animal이 가지는 메서드이고 각 동물이 몇번 불렸는지를 출력해줍니다. 이때 call이 실행된 횟수를 담을 필드(변수)가 Animal 객체에 필요하고, 그 필드명을 callCount로 했습니다. 근데 callCount의 경우 call()함수에서만 사용되어야하는데, 혹시 상속한 다른 클래스에서 잘못된 방법으로 해당 필드를 사용할까봐 상속한 클래스에서도 사용하지 못하게 Animal 객체 안에서만 쓸 수 있도록 private로 선언하였습니다.
이처럼 추상클래스 안에서만 사용할 필드의 경우, private 키워드를 사용하시면 됩니다.

0

추상클래스에서의 private은 추상클래스의 메서드에서 쓰이는 용도일 뿐입니다.

0

네, abstract class에서는 protected로 해야 realClass에서 extends가 가능합니다. abstract class도 실제로 존재하는 클래스이므로 protected가 아니면 상속이 안 됩니다.

abstract class AbstractClass {
  protected readonly a: string = "init";
  protected b: number = 1;
  c: string = "기본값이 public";

  abstract method(a: string): void;

  method2() {
    console.log(this.a);
    console.log(this.b);
    console.log(this.c);
  }
}

class realClass extends AbstractClass {
  method(a: string) {
    console.log(this.a);
    console.log(this.b);
    console.log(this.c);
  }
}

const rC = new realClass();
rc.a // 'error';