프로그램 개발을 유연하고 변경이 용이하게 한다.
개발과 보수를 간편하게한다.
직관적인 코드분석이 가능
클래스 요소
맴버(member) : 필드 생성자 메소드를 말한다.
필드(field)
생성자(constructor)
메소드(method)
인스턴스: new 연산자로 생성된 객체
class Person{
name: string; //필드
constructor(name:string) { //생성자
this.name = name;
}
say() { //메소드
return `hello mynameis ${this.name}`
}
}
let person = new Person("tom") //인스턴스 생성
접근제어자
public : 프로그램내에 선언된 맴버들이 자유롭게 접근가능
private: 멤버가 포함된 클래스 외부에서의 접근을 막는다.
protected: 멤버가 포함된 클래스와 하위 클래스 외부에서의 접근을 막는다.(선언 된 클래스와 상속받은 자식 클래스만 사용 가능)
Getters & Setters / readonly / static
readonly: 읽기 전용으로 설정해 변경할 수 없다. 선언될 때와 생성자(constructor)에서 값을 설정하면 이후 수정할 수 없다.
static: 각 인스턴스가 아닌 클래스 자체에서 보이는 전역 멤버를 생성
상속
extends 키워드로 상속 받을 수 있다.
class Animal{
move(distanceInMeters:number){
console.log('Animalmoved${distanceInMeters}');
}
}
class Dog extends Animal{ //Animal을 상속 받는다.
makeSound(){
console.log("멍멍!");
}
}
const dog = new Dog(); //인스턴스로 선언
dog.move(10); //부모 class Animal에 있는 메서드를 사용
dog.makeSound();
추상클래스
다른 클래스들이 파생될 수 있는 기초 클래스
직접 인스턴스화 할 수 없다.
abstract 키워드로 추상 클래스, 추상 메소드를 정의한다.
추상 메소드는 클래스에서 구현하지 않고 파생된 클래스에서 구현해야 한다.