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