Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin basic inheritance solution

Tags:

java

oop

kotlin

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?

like image 519
Waqar Haider Avatar asked May 26 '26 08:05

Waqar Haider


1 Answers

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

}
like image 62
D3xter Avatar answered May 30 '26 02:05

D3xter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!