객체 지향 프로그래밍의 4가지 특징

이희제·2024년 5월 26일
post-thumbnail

객체 지향 프로그래밍(OOP, Object-Oriented Programming)은 프로그램을 객체 단위로 나누어 구조화하고 설계하는 프로그래밍 패러다임이다. OOP는 코드의 재사용성과 유지보수성을 높이기 위해 널리 사용된다. 객체 지향의 핵심 개념인 4가지 특징에 대해 알아보자.

1. 캡슐화 (Encapsulation)

캡슐화는 객체의 상태(데이터)와 행동(메서드)을 하나로 묶고, 외부에서 객체의 내부 상태를 직접 접근하지 못하도록 제한하는 것이다. 이를 통해 데이터의 무결성을 유지하고, 객체 간의 상호 작용을 명확히 정의할 수 있다.

  • 예시:

    class Person {
      constructor(name, age) {
        this._name = name;
        this._age = age;
      }
    
      get name() {
        return this._name;
      }
    
      set name(newName) {
        this._name = newName;
      }
    
      get age() {
        return this._age;
      }
    
      set age(newAge) {
        if (newAge > 0) {
          this._age = newAge;
        }
      }
    }

2. 상속 (Inheritance)

상속은 기존 클래스(부모 클래스 또는 슈퍼 클래스)의 속성과 메서드를 새로운 클래스(자식 클래스 또는 서브 클래스)가 물려받아 사용하는 것이다. 이를 통해 코드의 재사용성을 높이고, 계층 구조를 형성하여 공통된 기능을 공유할 수 있다.

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

let dog = new Dog('Rex');
dog.speak(); // Rex barks.

3. 다형성 (Polymorphism)

다형성은 여러 클래스가 동일한 메서드를 다른 방식으로 구현할 수 있는 능력을 말한다. 이를 통해 동일한 인터페이스를 사용하면서도 객체에 따라 다른 동작을 수행할 수 있다.

자바스크립트에서는 메서드 오버라이딩을 통해 다형성을 구현할 수 있다.

  • 메서드 오버라이딩: 자식 클래스에서 부모 클래스의 메서드를 재정의하여 다른 동작을 수행
class Shape {
  draw() {
    console.log('Drawing a shape');
  }
}

class Circle extends Shape {
  draw() {
    console.log('Drawing a circle');
  }
}

class Square extends Shape {
  draw() {
    console.log('Drawing a square');
  }
}

let shapes = [new Shape(), new Circle(), new Square()];
shapes.forEach(shape => shape.draw());
// Output:
// Drawing a shape
// Drawing a circle
// Drawing a square

추가로 메서드 오버로딩을 통해 다형성을 구현할 수 있다.

  • 메서드 오버로딩 (Method Overloading)

메서드 오버로딩은 같은 이름의 메서드를 여러 개 정의하고, 매개변수의 타입이나 개수에 따라 다른 메서드를 호출하는 것을 말한다. 자바스크립트는 메서드 오버로딩을 직접 지원하지 않지만, 많은 다른 언어에서는 이를 지원한다.

자바의 예시를 보자.

public class MathUtils {
    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {
        return a + b;
    }
}

MathUtils math = new MathUtils();
System.out.println(math.add(5, 3));       // Output: 8
System.out.println(math.add(5.0, 3.0));   // Output: 8.0

4. 추상화 (Abstraction)

추상화는 객체에서 공통된 속성과 행위를 추출 하는 것이다.

class CoffeeMachine {
  constructor(brand) {
    this.brand = brand;
  }

  brew() {
    this._heatWater();
    this._grindBeans();
    console.log('Brewing coffee...');
  }

  _heatWater() {
    console.log('Heating water...');
  }

  _grindBeans() {
    console.log('Grinding beans...');
  }
}

let myCoffeeMachine = new CoffeeMachine('JavaBrew');
myCoffeeMachine.brew();
// Output:
// Heating water...
// Grinding beans...
// Brewing coffee...
profile
그냥 하자

0개의 댓글