접근 제한자 ( Access Modifier )
- 타입 스크립트에서는 접근 제한자 (Access Modifier) 를 지원한다.
- 접근 제한자에는 public , private , protected 가 있다.
- 아무것도 표기하지 않고 작성하면 public 이다.
- private 을 사용하면 해당 클래스 내에서만 사용 가능하다. #을 붙여도 가능.
- protected 는 자식 클래스에서도 접근이 가능하지만, 클래스 인스턴스에서는 접근 불가.
- static 을 사용하면 클래스로 접근해야한다.
class Exam {
name: string
static nation: string = 'Korea'
private addr: string
protected age: number
constructor(name: string , addr: string, age: number){
this.name = name
this.addr = addr
this.age = age
}
const myInfo = new Exam('jin','seoul',28);
console.log(myInfo, Exam.nation)
// nation 은 static 으로 선언되었기 때문에 클래스 명.속성이름 으로 접근해야한다.
class Exam2 extends Exam {
constructor(name: string, addr: string, age: number){
super(name, addr, age)
}
showInfo(){
console.log(super.age, super.name)
// private 인 addr 은 자식 클래스에서 접근 불가능
}
추상 클래스
- 추상 클래스는 선언만 해주고, 상속을 통해서만 사용해야한다.
// 추상 클래스 선언
abstract class abCar {
color: string;
constructor(color: string) {
this.color = color;
}
start() {
console.log("start");
}
abstract doSomething(): void;
// 추상 함수는 부모클래스에서 이름만 선언하고 구체적인 기능은 상속받은 객체에서 구현해줘야한다.
}
// extends 로 상속 가능
class abBmw extends abCar {
constructor(color: string) {
super(color);
}
doSomething(): void {
console.log("do Something"); // 여기서 추상함수 기능 구현
}
}