반응형
객체지향 프로그래밍 (OOP; Object-Oriented Programming)
객체지향 프로그래밍(OOP; Object-Oriented Programming)은 데이터를 객체로 표현하고, 객체 간의 상호작용을 통해 프로그램을 구성하는 방식이다
OOP의 형태로 프로그래밍하면 다양한 장점이 있지만, 결국 핵심은 다음 두 가지로 정리할 수 있다
주요 장점
확장성과 유연성 향상, 그리고 결합도 감소
추상 클래스와 인터페이스 상속을 통해 한 번 작성한 코드를 여러 곳에서 재사용할 수 있으며 느슨한 결합을 구현할 수 있다. 이에따라 공통된 기능도 추상화되기 때문에 중복 코드 또한 감소시킬 수 있다
// 공통된 기능을 추상화한 인터페이스
interface Payment {
void processPayment();
}
// 다양한 결제 방식이 인터페이스를 구현
class CreditCardPayment implements Payment {
@Override
public void processPayment() {
System.out.println("신용카드 결제 완료.");
}
}
class PayPalPayment implements Payment {
@Override
public void processPayment() {
System.out.println("PayPal 결제 완료.");
}
}
// 느슨한 결합을 구현한 결제 처리 클래스
class PaymentProcessor {
private Payment payment;
public PaymentProcessor(Payment payment) {
this.payment = payment;
}
public void process() {
payment.processPayment();
}
}
// 실행 예시
public class Main {
public static void main(String[] args) {
PaymentProcessor processor1 = new PaymentProcessor(new CreditCardPayment());
processor1.process(); // 신용카드 결제 완료.
PaymentProcessor processor2 = new PaymentProcessor(new PayPalPayment());
processor2.process(); // PayPal 결제 완료.
}
}
코드의 가독성 향상으로 인한 편리한 유지보수
클래스와 객체를 사용하여 코드의 구조를 명확하게 표현할 수 있다. 따라서 절차적 프로그래밍보다 더 직관적인 코드 작성이 가능하다
캡슐화를 통해 데이터 보호 및 접근을 제한하여 수정이 필요한 기능을 담당하는 객체를 특정하고, 해당 부분만 수정하게끔 구현할 수 있다
class BankAccount {
private double balance; // 외부에서 직접 접근할 수 없음
public void deposit(double amount) {
if (amount > 0) balance += amount;
}
public double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(1000);
System.out.println(account.getBalance()); // 1000
}
}
'프로그래밍' 카테고리의 다른 글
프로그래밍의 추상화 (0) | 2025.03.11 |
---|