シリーズ: Angelia
java
50 行
· 更新日 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;
}
}
関連記事
Angelia
haskell
EN
更新日 2026-02-03
Adding.hs
Adding.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Adding.hs).
記事を読む →
Angelia
haskell
EN
更新日 2026-02-03
Area.hs
Area.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Area.hs).
記事を読む →
Angelia
haskell
EN
更新日 2026-02-03
Chess.hs
Chess.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Chess.hs).
記事を読む →
Angelia
haskell
EN
更新日 2026-02-03
ChessGraphics.hs
ChessGraphics.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/ChessGraphics.hs).
記事を読む →
Angelia
haskell
EN
更新日 2026-02-03
Examples.hs
Examples.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Examples.hs).
記事を読む →
Angelia
haskell
EN
更新日 2026-02-03
Fibonacci.hs
Fibonacci.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Fibonacci.hs).
記事を読む →