S SmartDocs
Serie: Angelia java 50 righe · Aggiornato 2026-09-27

BankAccount.java

Angelia/Java/Week_6_7/code/01_encapsulation/BankAccount.java

/**
 * 銀行帳戶:示範「封裝」(encapsulation)。
 *
 * 資料不變量(data invariant):balance >= 0
 * 因為 balance 是 private,外界不可能寫 account.balance = -500;
 * 唯一能改變餘額的路徑是 deposit / withdraw,而這兩個方法都會守住不變量。
 */
public class BankAccount implements Account {

    // 私有欄位:只有這個類別裡的程式碼看得到
    private int balance;

    /**
     * 建構子(constructor):確保物件「出生」時就處於合法狀態。
     * @param initialDeposit 開戶金額,前置條件:>= 0
     */
    public BankAccount(int initialDeposit) {
        if (initialDeposit < 0) {
            throw new IllegalArgumentException(
                    "開戶金額不可為負數:" + initialDeposit);
        }
        this.balance = initialDeposit;
    }

    @Override
    public void deposit(int amount) {
        if (amount < 0) {                       // 違反前置條件 → 拒絕
            throw new IllegalArgumentException("存款金額不可為負數:" + amount);
        }
        this.balance = this.balance + amount;   // 不變量仍成立
    }

    @Override
    public void withdraw(int amount) {
        if (amount < 0) {
            throw new IllegalArgumentException("提款金額不可為負數:" + amount);
        }
        if (amount > this.balance) {            // 物件目前的「狀態」不允許此操作
            throw new IllegalStateException(
                    "餘額不足:餘額 " + this.balance + ",欲提領 " + amount);
        }
        this.balance = this.balance - amount;   // 因為 amount <= balance,結果仍 >= 0
    }

    /** Getter:讓外界「讀」得到餘額,但「寫」不到。 */
    @Override
    public int getBalance() {
        return this.balance;
    }
}

Articoli correlati