2017-05-28 47 views
3

如何使新SavingAccount使用init值ownerbalance科特林基本的继承解决方案

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,没有默认值?

回答

7

你可以用普通的构造函数,参数(因此无属性)实现它,并将其传递到您的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) { 

} 
+0

工作,但默认值有点儿很奇怪,因为我必须在每一个孩子班。一遍又一遍...... –

+0

覆盖函数的重写函数[默​​认参数](https://kotlinlang.org/docs/reference/functions.html#default-arguments)会自动从重写的函数中获取默认值(事实上,甚至无法指定其他默认值)。它看起来像构造函数不这样工作。 – Jesper

+0

@Jesper它的不同。在储蓄账户构造函数内部,我们并不是真正压倒银行的属性,这就是为什么我们必须声明默认值 – D3xter

2

更改您的类声明

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