3

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?

2 Answers 2

7

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) {

}
Sign up to request clarification or add additional context in comments.

3 Comments

worked but the default values are kinda very strange, because i have to do in every child class. over and over...
Overriding functions where the overridden function has default arguments automatically get the defaults from the overridden function (in fact, it isn't even possible to specify other defaults). It looks like constructors don't work that way.
@Jesper Its different. Inside the Saving-Account constructor we are not really overriding the properties of Banking, thats why we must declare default values
2

Change your class declaration to

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.