系列: Angelia
java
26 行
· 更新于 2026-09-27
SavingsAccount.java
Angelia/Java/Week_6_7/code/03_inheritance_lsp/SavingsAccount.java
/**
* 儲蓄帳戶:繼承 BankAccount,補上 withdraw 的實作。
*
* SavingsAccount 的契約(比 BankAccount 更明確):
* withdraw(amount):若 amount <= balance 則扣款並回傳 true;
* 否則不改變狀態並回傳 false。
* 資料不變量:balance >= 0(繼承自父類別,且永遠成立)
*/
public class SavingsAccount extends BankAccount {
public SavingsAccount() {
super(); // 呼叫父類別的建構子(建構子「不會」被繼承,要自己寫)
}
@Override
public boolean withdraw(int amount) {
if (amount < 0) {
throw new IllegalArgumentException("提款金額不可為負數:" + amount);
}
if (this.balance < amount) {
return false; // 餘額不足:拒絕,狀態不變
}
this.balance = this.balance - amount; // protected 欄位:子類別可直接存取
return true;
}
}
相关文章
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).
阅读文章 →