展如下的BankAccount类新类CheckingAccount对每次存款和取款都收取1块钱的手续费。scalaclass BankAccountinitialBalance Double private var balance = initialBalance def depositamount Double = balance += amount; balance
class BankAccount(initialBalance: Double) {
private var balance = initialBalance
def deposit(amount: Double) = {
balance += amount;
balance
}
def withdraw(amount: Double) = {
balance -= amount;
balance
}
}
class CheckingAccount(initialBalance: Double) extends BankAccount(initialBalance) {
override def deposit(amount: Double): Double = {
super.deposit(amount) - 1
}
override def withdraw(amount: Double): Double = {
super.withdraw(amount) - 1
}
}
在上述代码中,BankAccount类表示一个银行账户,CheckingAccount类是对BankAccount类的扩展,每次存款和取款都会收取1块钱的手续费。在CheckingAccount类中,通过使用super关键字调用BankAccount类的deposit和withdraw方法,并在其基础上减去1来实现手续费的收取
原文地址: https://www.cveoy.top/t/topic/hOgK 著作权归作者所有。请勿转载和采集!