1) 프로그램을 보다 유연하고 변경이 용이하게 만들 수 있다.
2) 코드의 변경을 최소화하고 유지보수를 하는 데 유리하다.
3) 코드의 재사용을 통해 반복적인 코드를 최소화하고, 코드를 최대한 간결하게 표현할 수 있다.
4) 인간 친화적이고 직관적인 코드를 작성하기에 용이하다.
예를 들어, 자동차와 오토바이는 모두 이동 수단이고, 전진과 후진을 할 수 있다는 공통점이 있다.
자동차와 오토바이라는 하위 클래스들의 공통적인 기능(전진과 후진)을 추출하여 이동 수단이라는 상위 클래스에 정의했다.
추상화를 구현할 수 있는 문법 요소로는
추상 클래스(abstract class)와 인터페이스(interface)가 있다.
// 추상 클래스
class Shape {
protected: int x, y;
public:
void setOrigin(int x, int y){
this->x = x;
this->y = y;
}
virtual void draw() = 0;
};
// 파생 클래스
class Rectangle : public Shape {
private:
int width, height;
public:
void setWidth(int w) {width = w;}
void setHeight(int h) {height = h;}
void draw() {cout << "Rectangle Draw" << endl;} // 재정의
};
int main(){
Shape *ps = new Rectangle();
// Shape s; 선언 시 에러!
ps->draw(); delete ps;
}
#define interface struct
interface IPlay
{
virtual void Play()=0;
};
class Man:public IPlay
{
string name;
public:
Man(string name)
{
this->name = name;
}
virtual void Play()
{
cout<<name<<" 연주하다."<<endl;
}
};
void Concert(IPlay *iplay)
{
iplay->Play();
}
int main()
{
Man *man = new Man("홍길동");
Concert(man);
delete man;
return 0;
}
// 부모 클래스
class Car {
public:
int speed; int gear; string color;
void setGear(int newGear) { gear = newGear;}
void speedUp(int increment) { speed += increment;}
void speedDown(int decrement) {speed -= decrement;}
};
// 자식 클래스
class SportsCar : public Car {
bool turbo;
public:
void setTurbo(bool newValue) {turbo = newValue;}
};
int main() {
SportsCar c;
c.color = "Red";
c.setGear(3);
c.speedUp(100);
c.speedDown(30);
c.setTurbo(true);
}
// 부모 클래스
class Mammal {
virtual void move() = 0;
virtual void eat() = 0;
virtual void speak() = 0;
};
// 자식 클래스
class Lion : public Mammal {
void move() {cout << "사자의 move() << endl;}
void eat() {cout << "사자의 eat() << endl;}
void speak() {cout << "사자의 speak() << endl;}
};
public class Rectangle {
Rectangle(int width, int height) { this(0, 0, width, height);}
Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;}
}
참고
https://www.codestates.com/blog/content/객체-지향-프로그래밍-특징
https://csj000714.tistory.com/408
https://ehclub.co.kr/2136
Power C++