[typescript] protected 접근 제어자와 메서드 오버라이딩

접근 제어자

타입스크립트에서 protected 접근 제어자는 클래스 멤버에 접근을 제한하는 데 사용됩니다. protected로 선언된 멤버는 해당 클래스나 그 클래스를 상속받은 클래스에서 접근할 수 있습니다.

아래는 protected 접근 제어자를 사용한 예제입니다:

class Person {
    protected name: string; // protected 멤버

    constructor(name: string) {
        this.name = name;
    }
}

class Employee extends Person {
    private department: string;

    constructor(name: string, department: string) {
        super(name);
        this.department = department;
    }

    public getDetails(): string {
        return `${this.name} works in ${this.department} department`;
    }
}

let emp = new Employee("Alice", "Sales");
console.log(emp.getDetails()); // Alice works in Sales department
console.log(emp.name); // Error: Property 'name' is protected and only accessible within class 'Person' and its subclasses

메서드 오버라이딩

타입스크립트는 메서드 오버라이딩 기능을 제공합니다. 이는 하위 클래스에서 상위 클래스의 메서드를 다시 정의해야 하는 경우에 유용합니다. 메서드 오버라이딩을 구현하려면 메서드에 override 키워드를 사용하고, 해당 메서드를 protected 또는 public으로 선언해야 합니다.

다음은 메서드 오버라이딩을 사용한 예제입니다:

class Animal {
    protected makeSound(): string {
        return "Some sound";
    }
}

class Dog extends Animal {
    protected makeSound(): string { // 메서드 오버라이딩
        return "Woof! Woof!";
    }
}

let dog = new Dog();
console.log(dog.makeSound()); // Woof! Woof!

위의 예제를 통해 protected 접근 제어자와 메서드 오버라이딩이 어떻게 사용되는지 이해할 수 있습니다. 이러한 기능을 통해 코드를 보다 유지보수하기 쉽고 확장 가능하도록 만들 수 있습니다.

참고 문헌: