-
2023 - 08 - 01 타입스크립트 : 객체지향 프로그래밍, 클래스, 생성자, 상속, 클래스 접근 제한자 public, private, protected, 부모클래스, 자식클래스, extends, 오버라이딩Today I Learned/TIL 08 2023. 8. 1. 19:55
클래스는 객체를 만들기 위한 틀 (template)
타입스크립트에서 클래스를 정의하기 위해 class 키워드를 사용하고,
클래스의 속성과 매서드를 정의한 뒤, new 키워드를 사용해서 객체를 생성할 수 있다.
객체는 클래스를 기반으로 생성되며, 클래스의 인스턴스(instance)라고도 한다.
class Person { name: string; age: number; constructor(name: string, age: number) { // 생성자 this.name = name; this.age = age; } sayHello() { console.log(`안녕하세요! 제 이름은 ${this.name}이고, 나이는 ${this.age}살입니다.`); } } const person = new Person('Spartan', 30); person.sayHello();
생성자(constructor) : 클래스의 인스턴스를 생성하고 초기화하는데 사용된다.
생성자는 클래스 내에 오직 하나만 존재할 수 있으며, 보통 생성자로 객체 속성을 초기화하는 것 뿐 아니라
객체가 생성이 될 때 꼭 되어야 하는 초기화 로직을 집어넣기도 한다.
예를들어, DBConnector라는 클래스가 있다면 이 클래스 타입이 객체가 생성될 때 생성자에서 DB연결을 미리 해주면 편하다.
클래스에서는 속성과 매서드에 접근 제한자를 사용해, 접근을 제한할 수도 있다.
타입스크립트 접근 제한자
public 클래스 외부에서도 접근이 가능한 접근 제한자 접근 제한자가 선언이 안되어있다면, 기본적으로 접근 제한자는 public 이다. 보통은 클래스의 함수 중 민감하지 않은 객체 정보를 열람할 때나 누구나 해당 클래스의 특정 기능을 사용해야 할 때 많이 쓰인다 private 클래스 내부에서만 접근이 가능한 접근 제한자 보통은 클래스의 속성은 대부분 private으로 접근 제한자를 설정한다. 즉, 외부에서 직접적으로 객체의 속성을 변경할 수 없게 제한하는 것 클래스의 속성을 보거나 편집하고 싶다면 별도의 getter/setter 메서드를 준비해놓는 것이 관례 protected 클래스 내부와 해당 클래스를 상속받은 자식 클래스에서만 접근이 가능한 접근 제한자
class Person { private name: string; private age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } public sayHello() { console.log(`안녕하세요! 제 이름은 ${this.name}이고, 나이는 ${this.age}살입니다.`); } }
상속(inheritance)
상속을 통해 기존 클래스의 속성과 매서드를 물려받아, 새로운 클래스를 정의할 수 있다.
타입스크립트에서 상속을 구현하려면 extends 키워드를 사용하면 됨
class Animal { name: string; constructor(name: string) { this.name = name; } makeSound() { console.log('동물 소리~'); } } class Dog extends Animal { age: number; constructor(name: string) { super(name); // super키워드 this.age = 5; } makeSound() { console.log('멍멍!'); // 부모의 makeSound 동작과 달라요! } eat() { // Dog 클래스만의 새로운 함수 정의 console.log('강아지가 사료를 먹습니다.'); } } class Cat extends Animal { // Animal과 다를게 하나도 없어요! } const dog = new Dog('누렁이'); dog.makeSound(); // 출력: 멍멍! const cat = new Cat('야옹이'); cat.makeSound(); // 출력: 동물 소리~
여기서 Animal을 부모클래스, Dog을 자식클래스라고 한다.
super 키워드는 자식클래스가 부모클래스를 참조하는데 사용하는 키워드
즉, 자식 클래스에서 생성자를 정의할 때에는, 부모 클래스의 생성자를 호출해야 하는데, 이 때 쓰임.
위의 함수를 보면 자식클래스에는 Dog과 Cat이 있는데, Dog 클래스에서는 생성자와 super키워드를 사용해 부모의 함수동작을 재정의한다. 이것을 '오버라이딩'이라고 한다.
반면, Cat 클래스에서는 생성자를 따로 작성하지 않고, 부모클래스의 생성자나 매서드를 그대로 사용한다.
'Today I Learned > TIL 08' 카테고리의 다른 글