如何使用SavingAccountowner的初始化值制作新的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
    }
}

和 child 类
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

最佳答案

您可以使用普通的Constructor-Arguments(因此没有Properties)来实现它,并将它们传递给BankAccount

class SavingAccount(owner: String,
        balance: Double,
        val increasedBy: Double = 0.05
): BankAccount(owner, balance) {

}
SavingAccount的默认值可以类似于BankAccount来定义:
class SavingAccount(owner: String = "Default Owner",
        balance: Double = 0.0,
        val increasedBy: Double = 0.05
): BankAccount(owner, balance) {

}

08-03 20:29