클래스

TypeScript 클래스는 객체지향 프로그래밍(OOP)을 지원하기 위해 제공되는 기능

 

기본 선언

class Architecture {
  name: string; // 클래스 속성
  year: number;

  constructor(name: string, year: number) { // 생성자
    this.name = name;
    this.year = year;
  }

  profile(): string { // 메서드
    return ` 건물명 : ${this.name}, 건물년수 : ${this.year} `;
  }
}

// 클래스 사용
const architecture = new Architecture("63빌딩", 39);
console.log(architecture.profile()); // Hello, my name is Alice and I am 30 years old.

console.log(Inheritance);

상속

이미 존재하는 클래스를 확장해 새로운 클래스를 만드는 기능

class Gun {
  constructor(public name: string) {}

  reload(): void {
    console.log(`${this.name}이 장전 되었습니다.`);
  }
}

class gun extends Gun {
  fire(): void {
    console.log(`${this.name}이 발사 되었습니다.`);
  }
}

// 사용 예시
const pistol = new gun("glock");
pistol.reload(); // glock이 장전 되었습니다.
pistol.fire(); // glock이 발사 되었습니다.

접근 제어자

 

1. public

어디서나 접근 가능.
명시적으로 선언하지 않으면 모든 멤버는 기본적으로 public으로 설정(기본 값)

class PublicExample {
    public name: string; // public 생략 가능
    constructor(name: string) {
        this.name = name;
    }
}
const PublicEx = new PublicExample("John");
console.log(PublicEx.name); // 접근 가능

 

2. private
클래스 내부에서만 접근 가능.
클래스 외부나 상속받은 클래스에서도 접근 불가

class PrivateExample {
    private secret: string;
    constructor(secret: string) {
        this.secret = secret;
    }
    getSecret() {
        return this.secret; // 내부에서 접근 가능
    }
}
const PrivateEx = new PrivateExample("hidden");
console.log(PrivateEx.getSecret()); // 접근 가능
// console.log(ex.secret); // 오류: private 속성

 

3. protected

클래스 내부와 상속받은 클래스에서 접근 가능
클래스 외부에서는 접근 불가

class Parent {
    protected value: number;
    constructor(value: number) {
        this.value = value;
    }
}
class Child extends Parent {
    getValue() {
        return this.value; // 상속받은 클래스에서 접근 가능
    }
}
const child = new Child(42);
console.log(child.getValue()); // 접근 가능
// console.log(child.value); // 오류: protected 속성

 

'TS' 카테고리의 다른 글

열거형 (1)  (0) 2024.12.04
클래스 (2)  (0) 2024.12.03
교차 타입  (0) 2024.11.29
리터럴 타입  (0) 2024.11.26
함수(Function)[2]  (0) 2024.11.25

+ Recent posts