OOP는 객체 지향 프로그래밍입니다. 네가지 특징으로 캡슐화, 상속, 다형성, 추상화가 있습니다.
OOP란 무엇인가?
OOP란 무엇인가
여는글
1. 캡슐화
class Person {
constructor(name) {
this.name = name;
}
introduce() {
return `내 이름은 ${this.name} 입니다.`;
}
}
const student = new Person("홍길동");
console.log(student.introduce()); // 내 이름은 홍길동 입니다.
// 객체를 한번 생성하면 객체 안의 데이터에 접근하지 않는다.
2. 상속
class Dog {
constructor(name) {
this.name = name;
this.type = "포유류";
}
bark() {
return "멍멍!";
}
}
class Poodle extends Dog {
constructor(name) {
super(name);
this.color = "갈색";
}
introduce() {
return "저는 푸들입니다";
}
}
const poodle = new Poodle("푸들이");
console.log(poodle.type); // 포유류
console.log(poodle.bark()); // 멍멍!
console.log(poodle.introduce()); // 저는 푸들입니다
3. 다형성
class Dog {
walk() {
return "산책 좋아요!";
}
}
class Cat {
walk() {
return "산책 싫어요!";
}
}
const dog = new Dog();
const cat = new Cat();
console.log(dog.walk()); // 산책 좋아요!
console.log(cat.walk()); // 산책 싫어요!
4. 추상화
class Animal {
constructor(name) {
this.name = name;
}
bark() {
throw new Error(
"추상 메서드는 오버라이딩(메서드 덮어쓰기) 하여 사용해야 합니다."
);
}
}
class Cat extends Animal {}
class Dog extends Animal {
bark() {
return "멍멍!";
}
}
const cat = new Cat("야옹이");
const dog = new Dog("멍멍이");
console.log(cat.bark()); // Error: 추상 메서드는 오버라이딩(메서드 덮어쓰기) 하여 사용해야 합니다.
console.log(dog.bark()); // 멍멍!