Waqar Haider
Waqar Haider

Reputation: 971

Kotlin basic inheritance solution

How do I make new SavingAccount with init values for owner and 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
    }
}

And the child class

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

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

and in main

fun main(args: Array<String>) {

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

How can I create SavingAccount for a new user, without default values?

Upvotes: 3

Views: 276

Answers (2)

D3xter
D3xter

Reputation: 6435

You can implement it with ordinary Constructor-Arguments (hence no Properties) and pass them into your BankAccount

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

}

Default values for SavingAccount can be defined similar to BankAccount:

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

}

Upvotes: 7

JB Nizet
JB Nizet

Reputation: 691645

Change your class declaration to

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

Upvotes: 2

Related Questions