TypeScript)클래스와 객체

Songss·2025년 1월 13일

TypeScript

목록 보기
7/10

구조체, 공용체, 열거형, 인터페이스, 클래스…

클래스는 연관된 변수와 함수들을 한 덩어리로 묶고 구조화한 객체 타입

함수와 변수를 이용하면 객체를 만들 수 있는데 .. 굳이 클래스를 사용하는 이유가 무엇일까?

함수와 변수를 조합해 객체를 만들 수 있음에도 불구하고, 클래스(class)를 사용하는 이유는 구조적 설계, 재사용성, 그리고 가독성 측면에서 많은 이점을 제공하기 때문입니다. 아래는 클래스 사용의 주요 이유를 정리한 내용입니다.

1. 객체 지향 프로그래밍(OOP)의 핵심 개념

클래스는 객체 지향 프로그래밍의 중요한 요소로, 다음과 같은 OOP의 원칙을 구현하는 데 유용합니다:

  • 캡슐화(Encapsulation):
    • 데이터를 은닉하고 필요한 인터페이스만 노출할 수 있습니다.
    • 클래스 내부에서만 접근 가능한 private 속성이나 메서드를 정의할 수 있습니다.
      class Person {
        private name: string;
      
        constructor(name: string) {
          this.name = name;
        }
      
        greet(): string {
          return `Hello, my name is ${this.name}`;
        }
      }
      
      const john = new Person("John");
      console.log(john.greet()); // Hello, my name is John
      // console.log(john.name); // 오류: 'name'은 private입니다.
  • 상속(Inheritance):
    • 클래스를 통해 코드 재사용이 가능하며, 부모 클래스를 확장해 자식 클래스에서 기능을 추가하거나 변경할 수 있습니다.
      class Animal {
        constructor(protected name: string) {}
        makeSound(): string {
          return `${this.name} makes a sound.`;
        }
      }
      
      class Dog extends Animal {
        makeSound(): string {
          return `${this.name} barks!`;
        }
      }
      
      const dog = new Dog("Buddy");
      console.log(dog.makeSound()); // Buddy barks!
  • 다형성(Polymorphism):
    • 동일한 메서드를 다른 방식으로 구현해 유연한 설계가 가능합니다.

2. 구조와 가독성

클래스는 복잡한 객체와 그 동작을 정의하는 데 있어 더 명확한 구조를 제공합니다.

  • 클래스는 설계도를 제공:
    • 객체의 속성과 동작(메서드)을 한 곳에 묶어서 정의합니다.
      class Car {
        constructor(private brand: string, private speed: number = 0) {}
      
        accelerate(amount: number): void {
          this.speed += amount;
        }
      
        getSpeed(): number {
          return this.speed;
        }
      }
      
      const car = new Car("Tesla");
      car.accelerate(50);
      console.log(car.getSpeed()); // 50
  • 가독성 향상:
    • 클래스 구조를 사용하면 여러 관련 함수와 데이터를 일관성 있게 관리할 수 있어, 코드가 더 읽기 쉽고 유지보수가 쉬워집니다.

3. 재사용성

  • 클래스를 통해 생성된 객체는 동일한 구조와 동작을 공유하므로 코드 재사용이 간단해집니다.
  • 상속을 활용해 기존 클래스를 기반으로 새로운 기능을 추가하는 방식으로 코드를 확장할 수 있습니다.

4. 추상화와 인터페이스

  • 클래스는 추상 클래스인터페이스를 통해 설계 단계에서 필요한 구조를 정의하고, 구현 단계에서 구체적인 동작을 추가할 수 있습니다.
    interface Shape {
      area(): number;
    }
    
    class Rectangle implements Shape {
      constructor(private width: number, private height: number) {}
    
      area(): number {
        return this.width * this.height;
      }
    }
    
    const rect = new Rectangle(10, 20);
    console.log(rect.area()); // 200

5. 인스턴스 관리와 메모리 효율

  • 클래스는 prototype을 통해 메서드와 속성을 공유하므로, 객체 생성 시 메모리를 절약할 수 있습니다.
    function PersonFunction(name) {
      this.name = name;
    }
    PersonFunction.prototype.greet = function () {
      return `Hello, my name is ${this.name}`;
    };
    
    const person1 = new PersonFunction("John");
    console.log(person1.greet()); // Hello, my name is John
    하지만 클래스는 이 과정을 더 간단하고 명확하게 표현합니다.

결론

클래스는 복잡한 객체를 설계하고 관리하기 쉽게 만들어 주며, 재사용성, 유지보수성, 확장성을 제공합니다.

객체를 단순히 만드는 것뿐만 아니라, 코드의 구조화, OOP 원칙 준수, 가독성 향상이 필요한 경우 클래스는 필수적입니다.

클래스 생성 실습

// 멤버 변수 == 속성 == 프로퍼티
// 멤버 함수 == 메소드

class Employee {
  // 직원 정보
  empName: string;
  age: number;
  empJob: string;

  printEmp = (): void => {
    console.log(`${this.empName} 의 나이는 ${this.age} 이고, 직업은 ${this.empJob} 입니다.`);
  };
}

// Employee 인스턴스 생성
const emp1 = new Employee();
emp1.empName = 'John Doe';
emp1.age = 30;
emp1.empJob = 'Software Engineer';

// printEmp() 호출
emp1.printEmp();

0개의 댓글