3
如何使新SavingAccount
使用init值owner
和balance
科特林基本的繼承解決方案
open class BankAccount(val owner: String = "Long John Silver", private var balance: Double = 0.00) {
constructor (amount: Double) : this() {
this.balance = amount
}
fun deposit(amount: Double){
this.balance += amount
}
fun withdraw(amount: Double){
this.balance -= amount
}
fun getBalance(): Double{
return this.balance
}
}
而子類
class SavingAccount(val increasedBy: Double = 0.05): BankAccount(){
fun addInterest(): Unit{
val increasedBy = (this.getBalance() * increasedBy)
deposit(amount = increasedBy)
}
}
,並在主
fun main(args: Array<String>) {
val sa = SavingAccount();// how to do this SavingAccount("Captain Flint", 20.00)
println(sa.owner)
println(sa.owner)
}
哪有我爲新用戶創建了SavingAccount
,沒有默認值?
工作,但默認值有點兒很奇怪,因爲我必須在每一個孩子班。一遍又一遍...... –
覆蓋函數的重寫函數[默認參數](https://kotlinlang.org/docs/reference/functions.html#default-arguments)會自動從重寫的函數中獲取默認值(事實上,甚至無法指定其他默認值)。它看起來像構造函數不這樣工作。 – Jesper
@Jesper它的不同。在儲蓄賬戶構造函數內部,我們並不是真正壓倒銀行的屬性,這就是爲什麼我們必須聲明默認值 – D3xter