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

PointsAccount.java

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

/**
 * 飛行常客點數帳戶:另一種完全不同的 Account 實作。
 *
 * 行為與 BankAccount 不同(開戶送 10000 點、每次存入加送 1%),
 * 但同樣遵守 Account 介面規定的前置/後置條件,
 * 因此任何「只認識 Account」的程式碼都能直接使用它。
 */
public class PointsAccount implements Account {

    private int points = 10000;   // 新會員禮:開戶就有 10000 點

    @Override
    public void deposit(int amount) {
        if (amount < 0) {
            throw new IllegalArgumentException("點數不可為負數:" + amount);
        }
        // 每次存入加送 1%(整數除法,不足 100 點就沒有紅利)
        this.points = this.points + amount + amount / 100;
    }

    @Override
    public void withdraw(int amount) {
        if (amount < 0 || amount > this.points) {
            throw new IllegalStateException("點數不足或金額不合法:" + amount);
        }
        this.points = this.points - amount;
    }

    @Override
    public int getBalance() {
        return this.points;
    }
}

Articoli correlati