구조체, 공용체, 열거형, 인터페이스, 클래스…
클래스는 연관된 변수와 함수들을 한 덩어리로 묶고 구조화한 객체 타입
함수와 변수를 조합해 객체를 만들 수 있음에도 불구하고, 클래스(class)를 사용하는 이유는 구조적 설계, 재사용성, 그리고 가독성 측면에서 많은 이점을 제공하기 때문입니다. 아래는 클래스 사용의 주요 이유를 정리한 내용입니다.
클래스는 객체 지향 프로그래밍의 중요한 요소로, 다음과 같은 OOP의 원칙을 구현하는 데 유용합니다:
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입니다.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!클래스는 복잡한 객체와 그 동작을 정의하는 데 있어 더 명확한 구조를 제공합니다.
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()); // 50interface 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()); // 200prototype을 통해 메서드와 속성을 공유하므로, 객체 생성 시 메모리를 절약할 수 있습니다.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();