Kotlin's main inheritance solution

How to create a new one SavingAccount

with init values ​​for owner

andbalance

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
    }
}

      

And the child class

class SavingAccount(val increasedBy: Double = 0.05): BankAccount(){

    fun addInterest(): Unit{
        val increasedBy = (this.getBalance() * increasedBy)
        deposit(amount = increasedBy)
    }
}

      

and mostly

fun main(args: Array<String>) {

    val sa = SavingAccount();// how to do this SavingAccount("Captain Flint", 20.00)
    println(sa.owner)
    println(sa.owner)
}

      

How to create SavingAccount

for a new user without default values?

+3


source to share


2 answers


You can implement it with normal constructor arguments (hence no properties) and pass them in your BankAccount

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

}

      



The default values ​​for SavingAccount

can be defined similarly BankAccount

:

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

}

      

+7


source


Change the class declaration to



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

      

+2


source







All Articles