[TIL] Day 42 : Object-Oriented Programming

Q·2024년 6월 15일

TIL

목록 보기
43/59

캡슐화 (Encapsulation)

객체 내부에 세부적인 사항을 외부에 노출시키지 않도록 감추는 것
데이터에 접근할 수 있는 방법을 제한

class User {
	private name: string; // name 변수를 외부에서 접근할 수 없게 만든다.
    private age: number; // age 변수를 외부에서 접근할 수 없게 만든다.
    
    setName(name: string) { // Private 속성을 가진 name 변수의 값을 변경합니다.
    	this.name = name;
    }
    
    getName() { // Private 속성을 가진 name 변수의 값을 조회합니다.
    	return this.name;
    }
    
    setAge(age: number) { // Private 속성을 가진 age 변수의 값을 변경합니다.
    	this.age = age;
    }
    
    getAge() { // Private 속성을 가진 age 변수의 값을 조회합니다.
    	return this.age;
    }
}
const user = new User(); // user 인스턴스 생성
user.setName('홍길동');
user.setAge(30);
console.log(user.getName()); // 홍길동
console.log(user.getAge()); // 30
console.log(user.name); // Error: User 클래스의 name 변수는 private로 설정되어 있어 바로 접근할 수 없습니다.

private : Access modifier
인스턴스 내부에서만 해당 변수에 접근이 가능하도록 제한하는 Typescript 문법

상속 (Inheritance)

하나의 클래스가 가진 특징(함수, 변수, 데이터)을 다른 클래스가 그대로 물려 받는 것
이미 정의된 상위 클래스의 특징을 하위 클래스에서 물려받아 코드의 중복을 제거하고 코드 재사용성을 증대

class Mother {
	constructor(name, age, tech) {
    	this.name = name;
        this.age = age;
        this.tech = tech;
    }
    getTech(){ return this.tech; }
}

class Child extends Mother{ // Mother 클래스를 상속받은 Child 클래스
	constructor(name, age, tech) // 자식 클래스 생성자
    	super(name, age, tech); // 부모 클래스의 생성자를 호출
    }
}

const child = new Child("홍길동, 30, "Node.js");
console.log(child.name); // 홍길동
console.log(child.age); // 30
console.log(child.getTech()); // 부모 클래스의 getTech 메서드 호출: Node.js

추상화 (Abstraction)

객체에서 공통된 부분을 모아 상위 개념으로 새롭게 정의

interface Human {
	name: string;
    setName(name);
    getName();
}

// interface에서 상속받은 properties와 methods는 구현하지 않을 경우 에러가 발생한다.
class Employee implements Human {
	constructor (public name: string) { }
    
    // Human interface에서 상속받은 method
    setName(name) { this.name = name; }
    
    // Human interface에서 상속받은 method 
    getName() { return this.name; }
}

const employee = new Employee("");
employee.setName("홍길동"); // Employee 클래스의 name을 변경하는 setter
console.log(employee.getName()); // Employee 클래스의 name을 조회하는 getter

interface: Class를 정의할 때 메소드와 속성만 정의하여 인터페이스에 선언된 properties 또는 methos의 구현을 강제하여 코드의 일관성을 유지

다형성 (Polymorphism)

하나의 객체(클래스)가 다양한 형태로 동작
객체가 가진 특성에 따라 같은 기능이 다르게 재구성
동일한 메서드나 함수명을 사용하더라도 클래스마다 그 메서드가 다르게 동작

class Person {
	constructor(name) { this.name = name; }
    
    buy() {}
}

class Employee extends Person {
	buy() { console.log(`${this.constructor.name} 클래스의 ${this.name}님이 물건을 구매하였습니다.`); }
}

class User extends Person {
	buy() { console.log(`${this.constructor.name} 클래스의 ${this.name}님이 물건을 구매하였습니다.`); }
}

const employee1 = new Employee("홍길동");
const employee2 = new Employee("홍길서");
const user1 = new User("홍길남");
const user2 = new User("홍길북");

const personsArray = [employee1, employee2, user1, user2];
// personsArray에 저장되어 있는 Employee, User 인스턴스들의 buy 메소드를 호출합니다.
personsArray.forEach((person) => person.buy()};

// Employee 클래스의 홍길동님이 물건을 구매하였습니다.
// Employee 클래스의 홍길서님이 물건을 구매하였습니다.
// User 클래스의 홍길남님이 물건을 구매하였습니다.
// User 클래스의 홍길북님이 물건을 구매하였습니다.

0개의 댓글