객체 지향 프로그래밍(Object-Oriented Programming, OOP)은 프로그램을 객체의 모임으로 보는 프로그래밍 패러다임이다. 여기서 객체는 데이터와 이를 처리하는 메서드를 포함하고 있는 하나의 단위로 볼 수 있다.
이 OOP를 이루기 위해서 가지는 여러 가지 요소가 있으며, 주요 요소들은 다음과 같다.
1. 클래스와 객체
- 클래스(Class): 클래스는 객체를 정의하는 틀 또는 설계도라고 할 수 있다. 클래스는 객체의 속성과 행위를 정의한다.
- 객체(Object): 객체는 클래스의 인스턴스(instance)로 설계도인 클래스를 바탕으로 실제 사용할 수 있게 만든 구현체라고 할 수 있다.
2. 캡슐화(Encapsulation)
캡슐화는 객체의 속성과 메서드를 하나로 묶고, 객체의 내부 상태를 외부에서 직접 접근하지 못하도록 하는 것이다. 이를 통해 데이터의 무결성을 보호하고, 객체 간의 인터페이스를 명확히 한다.
캡슐화는 아래와 같은 장점을 제공한다.
- 정보 은닉: 객체의 내부 상태를 숨기고, 공개된 메서드를 통해서만 접근할 수 있도록 한다.
- 변경 용이성: 내부 구현을 변경하더라도 외부 코드에 영향을 미치지 않는다.
- 코드 재사용성: 객체 단위로 코드를 모듈화 하여 재사용할 수 있다.
3. 상속(Inheritance)
상속은 기존 클래스(부모 클래스 또는 슈퍼 클래스)의 속성과 메서드를 새로운 클래스(자식 클래스 또는 서브 클래스)가 물려받는 것이다. 상속을 통해 코드의 재사용성을 높이고, 계층적인 관계를 형성할 수 있다.
상속의 장점은 아래와 같다.
- 코드 재사용: 공통된 기능을 부모 클래스에 정의하여 자식 클래스에서 재사용할 수 있다.
- 유지 보수성 향상: 변경 사항을 부모 클래스에만 적용하면, 이를 상속받는 모든 자식 클래스에 자동으로 반영된다.
- 다형성 지원: 상속을 통해 부모 클래스 타입의 참조 변수로 자식 클래스를 다룰 수 있다.
4. 다형성(Polymorphism)
다형성은 같은 이름의 메서드가 서로 다른 클래스에서 다르게 동작할 수 있는 능력을 의미한다. 다형성은 주로 다음 두 가지 형태로 나타난다.
- 오버로딩(Overloading): 같은 이름의 메서드를 매개변수의 타입이나 개수에 따라 다르게 정의하는 것.
- 오버라이딩(Overriding): 부모 클래스에서 정의한 메서드를 자식 클래스에서 재정의하여 사용하는 것.
다형성의 장점은 아래와 같다.
- 유연성: 동일한 인터페이스를 통해 다른 동작을 구현할 수 있다.
- 확장성: 새로운 클래스를 추가하더라도 기존 코드를 수정하지 않고 기능을 확장할 수 있다.
- 유지 보수성 향상: 코드를 더 이해하기 쉽고 관리하기 쉽게 만든다.
5. 추상화(Abstraction)
추상화는 복잡한 시스템에서 필요한 부분만 간추려서 모델링하는 것이다. 객체 지향 프로그래밍에서 추상화는 주로 클래스와 인터페이스를 통해 구현된다.
추상화의 장점은 아래와 같다.
- 복잡성 감소: 불필요한 세부 사항을 감추고, 중요한 기능에 집중할 수 있다.
- 코드 가독성 향상: 중요한 로직을 명확하게 표현하여 코드의 가독성을 높인다.
- 유지 보수성 향상: 코드 구조를 단순화하여 유지 보수를 쉽게 한다.