객체 지향 프로그래밍(OOP) (Object-oriented programming)
컴퓨터 프로그램을 객체의 모임으로 파악하려는 프로그래밍 패러다임
객체들은 서로 메세지를 주고 받을 수 있고 데이터 처리 가능
OOP의 장점
- 프로그램을 유연하고 변경이 용이하게 만든다
-프로그램의 개발과 보수를 간편하게 만든다
-직관적인 코드 분석이 가능
--OOP의 중요 특성 : 강한 응집력과 약한 결합력 지향
Class 요소
멤버(member)/필드(field)/생성자(constructor)/메소드(method)
(필드,생성자,메소드=멤버)
인스턴스 : new 연산자에 의해서 생성된 객체
//Person의 class 멤버는 name, constructor, say()
class Person {
name: string;
constructor(name: string) {
this.name = name; //클래스 안에서 this. : 클래스의 멤버를 의미
}
say() {
return "Hello, My name is "+ this.name;
}
}
//new를 사용하여 Person클래스의 인스턴스 생성
let person = new Person("june");
접근 제어자 (public, protected, private)
✔️속성 또는 메소드의 접근을 제한하기 위해 사용함
public > protected > private
(Java와 다르게 package개념이 없어 default접근제어자는 존재 x)
• public 접근제어자
typescript에서 멤버는 기본적으로 public으로 선언
class Animal {
public name: string //명시적으로 pulic 선언 가능
constructor(theName: string) {
this.name = theName;
}
}
new Animal("Cat").name ; //프로그램 내에서 선언된 멤버들이 자유롭게 접근 가능
• private 접근제어자
멤버가 포함된 클래스 외부에서의 접근을 막음
class Animal {
private name: string
constructor(theName: string) {
this.name = theName;
}
}
new Animal("Cat").name
// Error: Property 'name' is private and only accessible within class 'Animal'
• protected 접근제어자
멤버가 포함된 클래스와 그 하위 클래스를 제외한 외부에서의 접근을 막음(상속 개념 필요)
class Person {
protected name: string
constructor(name: string) {
this.name = name;
}
}
class Employee extends Person {//부모 클래스에 상속됨
private department: string
constructor(name: string, department: string) {
super(name);
this.department = department;
}
public getElevatorPitch() {
return 'Hello, my name is ${this.name} and I work in ${this.department}.';
}
}
let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name);
// Error: Property 'name' is protected and only accessible within class 'Person' and its subclasses.
//기초 클래스=상위클래스=superclass
class Animal {
move(distanceInMeters: number) {
console.log(`Animal moved ${distanceInMeters}m.`);
}
}
// 파생된 클래스=하위클래스=subclass
//extends 키워드로 Animal이라는 기초 클래스에서 Dog클래스가 파생됨
class Dog extends Animal {
makeSound() {
console.log("멍멍!");
}
}
const dog = new Dog();
dog.move(10);
dog.makeSound();
• getters&setters
비공개로 설정하려는 속성은 private로 설정하고 속성값을 읽고 수정하는 getter/setter 함수를 사용
- class의 속성에 직접 접근하는 것을 막음
(속성에 직접 접근하여 수정하면 데이터 무결성이 깨질 수 있음)
- 각 객체의 멤버에 접근하는 방법을 세밀하게 제어 가능
class Person {
private _name: string
get name() {
return this._name;
}
set name(name: string) {
if (name.length > 10) {
throw new Error("name too long")
}
this._name = name;
}
}
• readonly
읽기만 가능한 속성을 선언하기 위해 사용
선언될때나 생성자에서 값을 설정하면 이후 수정 불가능
class Person{
readonly age: number = 20 // 선언 초기화
constructor(age: number) {
this.age = age;
}
}
person.age = 30;
// Error: Cannot assign to 'age' because it is a read-only property.
• static
전역 멤버(클래스의 모든 객체가 공유하는 멤버)를 선언할 때 사용
범용적으로 사용되는 값에 설정
class Grid {
static origin = { x: 0, y: 0 }
calculateDistanceFromOrigin(point: { x: number; y: number}) {
//"클래스명."을 앞에 붙여 static 멤버에 접근할 수 있음
let xDist = point.x - Grid.origin.x;
let yDist = point.y - Grid.origin.y;
return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
}
constructor(public scale: number) {}
}