S SmartDocs
系列: Angelia java 37 行 · 更新於 2026-09-27

BankAccount.java

Angelia/Java/Week_6_7/code/03_inheritance_lsp/BankAccount.java

/**
 * 抽象類別(abstract class):所有帳戶的共同部分。
 *
 * - 有欄位與具體方法(deposit、getBalance)可以讓子類別「繼承」重用;
 * - 不能直接 new BankAccount():它只是用來被 extends 的骨架。
 *
 * 契約(子類別都必須遵守):
 *   資料不變量:balance >= 0
 *   deposit(amount):前置條件 amount >= 0;後置條件 餘額增加 amount
 */
public abstract class BankAccount {

    /** protected:子類別可以直接讀寫,但無關的外部程式碼不行。 */
    protected int balance;

    public BankAccount() {
        this.balance = 0;
    }

    public void deposit(int amount) {
        if (amount < 0) {
            throw new IllegalArgumentException("存款金額不可為負數:" + amount);
        }
        this.balance = this.balance + amount;
    }

    public int getBalance() {
        return this.balance;
    }

    /**
     * 抽象方法:每種帳戶的提款規則不同,所以這裡只宣告、不實作。
     * 契約:嘗試提款並回報是否成功;成功時餘額減少 amount。
     * @param amount 前置條件:amount >= 0
     */
    public abstract boolean withdraw(int amount);
}

相關文章