
간단한 BankAccount 클래스 (짧고 쉬운 버전)
- BankAccount.java
java
public class BankAccount {
private String accountNumber;
private String ownerName;
private double balance;
// 생성자: 계좌번호, 계좌주, 초기입금
public BankAccount(String accountNumber, String ownerName, double initialDeposit) {
this.accountNumber = accountNumber;
this.ownerName = ownerName;
this.balance = Math.max(0, initialDeposit); // 초기입금이 음수면 0으로 설정
}
// 잔액 조회
public double getBalance() {
return this.balance;
}
// 입금
public void deposit(double amount) {
if (amount > 0) {
this.balance += amount;
System.out.println(amount + "원 입금되었습니다.");
} else {
System.out.println("입금액은 0보다 커야 합니다.");
}
}
// 출금 (성공하면 true, 실패하면 false)
public boolean withdraw(double amount) {
if (amount <= 0) {
System.out.println("출금액은 0보다 커야 합니다.");
return false;
}
if (amount > this.balance) {
System.out.println("잔액이 부족합니다.");
return false;
}
this.balance -= amount;
System.out.println(amount + "원 출금되었습니다.");
return true;
}
// 간단한 계좌 정보 출력
public void printAccountInfo() {
System.out.println("계좌주: " + this.ownerName + " | 계좌번호: " + this.accountNumber + " | 잔액: " + this.balance + "원");
}
}
- MainTest.java (테스트 코드)
java
public class MainTest {
public static void main(String[] args) {
BankAccount a = new BankAccount("111-111", "철수", 100000);
BankAccount b = new BankAccount("222-222", "영희", 5000);
a.printAccountInfo();
b.printAccountInfo();
System.out.println("--- 철수 거래 ---");
a.deposit(20000);
a.withdraw(50000);
a.withdraw(100000); // 실패(잔액 부족)
System.out.println("--- 영희 거래 ---");
b.withdraw(3000);
b.deposit(7000);
System.out.println("--- 최종 잔액 ---");
System.out.println("철수 잔액: " + a.getBalance() + "원");
System.out.println("영희 잔액: " + b.getBalance() + "원");
}
}
예상 콘솔 출력
계좌주: 철수 | 계좌번호: 111-111 | 잔액: 100000.0원
계좌주: 영희 | 계좌번호: 222-222 | 잔액: 5000.0원
--- 철수 거래 ---
20000.0원 입금되었습니다.
50000.0원 출금되었습니다.
잔액이 부족합니다.
--- 영희 거래 ---
3000.0원 출금되었습니다.
7000.0원 입금되었습니다.
--- 최종 잔액 ---
철수 잔액: 70000.0원
영희 잔액: 9000.0원
짧은 설명
- balance(잔액)는 private으로 숨겨 안전하게 관리합니다. 외부에서는 getBalance(), deposit(), withdraw() 메서드로만 접근합니다.
- deposit()과 withdraw()에서 잘못된 금액(음수 등)을 검사하여 계좌가 이상 상태가 되는 것을 막습니다.
'Java_language' 카테고리의 다른 글
| 자바의 static과 this에 대해서 (0) | 2025.12.01 |
|---|---|
| 자바 접근제어자(Access Modifier) (0) | 2025.12.01 |
| 클래스를 활용한 학생 정보 출력 프로그램 (0) | 2025.11.26 |
| 클래스 만들기 연습문제 (0) | 2025.11.26 |
| 클래스의 객체 생성 및 사용 (0) | 2025.11.26 |