Série: Angelia
java
33 linhas
· Atualizado 2026-09-27
AccountWithWithdrawalFees.java
Angelia/Java/Week_6_7/code/03_inheritance_lsp/AccountWithWithdrawalFees.java
/**
* 每次提款收 5 元手續費的帳戶。
*
* ★ 設計決定:它 extends BankAccount,而「不是」extends SavingsAccount。
*
* 若繼承 SavingsAccount,程式碼重用會更多,但會違反行為子型別:
* 對 SavingsAccount 而言「提領剛好等於餘額的金額」一定成功,
* 但在這裡會因為手續費而失敗——等著 SavingsAccount 行為的呼叫者就被騙了。
*
* 改成繼承 BankAccount(契約較寬鬆:只說「嘗試提款並回報結果」),就沒有違約問題。
* 這就是「重用最方便的父類別」與「行為上正確的父類別」之間的張力。
*/
public class AccountWithWithdrawalFees extends BankAccount {
public static final int FEE = 5; // static final:常數,命名全大寫
public AccountWithWithdrawalFees() {
super();
}
@Override
public boolean withdraw(int amount) {
if (amount < 0) {
throw new IllegalArgumentException("提款金額不可為負數:" + amount);
}
int total = amount + FEE;
if (this.balance < total) {
return false;
}
this.balance = this.balance - total;
return true;
}
}
Artigos relacionados
Angelia
haskell
EN
Atualizado 2026-02-03
Adding.hs
Adding.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Adding.hs).
Ler artigo →
Angelia
haskell
EN
Atualizado 2026-02-03
Area.hs
Area.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Area.hs).
Ler artigo →
Angelia
haskell
EN
Atualizado 2026-02-03
Chess.hs
Chess.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Chess.hs).
Ler artigo →
Angelia
haskell
EN
Atualizado 2026-02-03
ChessGraphics.hs
ChessGraphics.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/ChessGraphics.hs).
Ler artigo →
Angelia
haskell
EN
Atualizado 2026-02-03
Examples.hs
Examples.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Examples.hs).
Ler artigo →
Angelia
haskell
EN
Atualizado 2026-02-03
Fibonacci.hs
Fibonacci.hs — haskell source code from the Angelia learning materials (Angelia/Haskell/Fibonacci.hs).
Ler artigo →