본문 바로가기
Javascript

OOP(3)

by Doromi 2023. 11. 5.
728x90
반응형
 은행 계좌와 트랜잭션을 모델링하는 객체 지향 프로그래밍(OOP)의 예시입니다. 은행 계좌와 트랜잭션을 모델링하는 객체 지향 프로그래밍(OOP)의 예시입니다.
// 은행 계좌 클래스 정의
class BankAccount {
  constructor(accountNumber, accountHolder, balance) {
    this.accountNumber = accountNumber;
    this.accountHolder = accountHolder;
    this.balance = balance;
    this.transactions = [];
  }

  deposit(amount) {
    if (amount > 0) {
      this.balance += amount;
      this.transactions.push(`입금: +${amount}`);
    }
  }

  withdraw(amount) {
    if (amount > 0 && amount <= this.balance) {
      this.balance -= amount;
      this.transactions.push(`출금: -${amount}`);
    }
  }

  getBalance() {
    console.log(`계좌 잔액: ${this.balance}`);
  }

  showTransactions() {
    console.log("트랜잭션 기록:");
    this.transactions.forEach((transaction, index) => {
      console.log(`${index + 1}. ${transaction}`);
    });
  }
}

// 은행 계좌 객체 생성
const myAccount = new BankAccount("12345", "John Doe", 1000);

// 계좌 조작
myAccount.deposit(500);
myAccount.withdraw(200);
myAccount.getBalance();
myAccount.showTransactions();
 BankAccount 클래스를 정의하고, 은행 계좌와 관련된 속성과 메서드를 포함합니다. deposit 메서드로 돈을 입금하고, withdraw 메서드로 돈을 출금할 수 있습니다. getBalance 메서드는 계좌 잔액을 출력하고, showTransactions 메서드로 이전 트랜잭션 기록을 표시합니다.

이를 통해 객체 지향 프로그래밍의 다른 측면을 보여주고 있으며, 클래스를 사용하여 실제 세계의 엔티티를 모델링하는 방법을 보여줍니다.
728x90
반응형

'Javascript' 카테고리의 다른 글

Async Functions in Javascript  (0) 2024.04.01
OOP(5)  (0) 2023.11.07
OOP(4)  (0) 2023.11.06
OOP(2)  (0) 2023.11.05
OOP  (0) 2023.11.05