Kotlin基本继承解决方案

时间:2017-05-28 10:25:07

标签: java oop kotlin

如何使用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
    }
}

和儿童班

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

2 个答案:

答案 0 :(得分:7)

您可以使用普通的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) {

}

答案 1 :(得分:2)

将您的班级声明更改为

class Contact(models.Model):
    company = models.CharField(max_length=200, blank=True)
    vatkey = models.CharField(max_length=200, blank=True)