Start learning free

LESSON 65 OF 70 · PROJECTS: OBJECT-ORIENTED

Bank Account in Kotlin: Encapsulation with a Private Balance

Practice Read the full explanation

Build a BankAccount class that keeps its balance private and lets other code change it only through methods that check the rules. This is encapsulation: the object protects its own data.

Private balance. Declare private var balance: Double = initialBalance inside the class, so only the class can change it.

What the class must have (Kotlin):

  • The primary constructor class BankAccount(initialBalance: Double): creates an account that starts with the given balance.
  • fun deposit(amount: Double): adds amount to the balance. If amount is zero or negative, do nothing (no error, the balance stays the same).
  • fun withdraw(amount: Double): Boolean: if amount is zero or negative, or larger than the balance, change nothing and return false. Otherwise subtract it from the balance and return true. Withdrawing exactly the whole balance is allowed (the balance becomes 0).
  • fun getBalance(): Double: returns the current balance. It is the only way for outside code to read it.

Kotlin's Double prints as 120.0, so the driver uses .toInt() to print 120.

The driver. The driver at the end of the starter code is already written and uses your class. It runs these checks:

class Solution {
    fun mainFunction() {
        val account = BankAccount(100.0)
        account.deposit(50.0)
        account.withdraw(30.0)
        account.withdraw(200.0)
        println("Balance: " + account.getBalance().toInt())
        account.deposit(-20.0)
        account.deposit(0.0)
        account.withdraw(-5.0)
        println("Balance: " + account.getBalance().toInt())
        if (account.withdraw(120.0)) {
            println("Withdrew all")
        }
        println("Balance: " + account.getBalance().toInt())
        if (!account.withdraw(1.0)) {
            println("Rejected")
        }
    }
}

Walk through it: start with 100, deposit 50 (150), withdraw 30 (120), withdraw 200 is refused (still 120). Then deposit -20, deposit 0 and withdraw -5 are all ignored (still 120). Withdrawing 120 succeeds and empties the account, so the balance is 0, and withdrawing 1 more is refused.

Expected output:

Balance: 120
Balance: 120
Withdrew all
Balance: 0
Rejected

Both deposit and withdraw start with a guard that rejects amount <= 0. Write the guard first, then the change to the balance.

private var balance: Double = initialBalance inside the class body.

if (amount <= 0 || amount > balance) return false, then balance -= amount and return true.

class BankAccount(initialBalance: Double) {
    private var balance: Double = initialBalance

    fun deposit(amount: Double) {
        if (amount <= 0) return
        balance += amount
    }

    fun withdraw(amount: Double): Boolean {
        if (amount <= 0 || amount > balance) return false
        balance -= amount
        return true
    }

    fun getBalance(): Double {
        return balance
    }
}

class Solution {
    fun mainFunction() {
        val account = BankAccount(100.0)
        account.deposit(50.0)
        account.withdraw(30.0)
        account.withdraw(200.0)
        println("Balance: " + account.getBalance().toInt())
        account.deposit(-20.0)
        account.deposit(0.0)
        account.withdraw(-5.0)
        println("Balance: " + account.getBalance().toInt())
        if (account.withdraw(120.0)) {
            println("Withdrew all")
        }
        println("Balance: " + account.getBalance().toInt())
        if (!account.withdraw(1.0)) {
            println("Rejected")
        }
    }
}

STEP 1 OF 11
    Ctrl + Enter to check

    KOTLIN · PROJECTS: OBJECT-ORIENTED

    Bank Account in Kotlin, explained

    Problem overview

    The lesson asks for a BankAccount class whose balance cannot be changed from outside. Other code can only ask the account to deposit or withdraw, and the account decides whether the request is allowed. Hiding data behind methods that enforce rules is called encapsulation.

    The class needs four members:

    • a constructor taking the starting balance as a Double;
    • deposit(amount), which adds a positive amount and silently ignores zero or negative ones;
    • withdraw(amount): Boolean, which returns false and changes nothing if the amount is not positive or is more than the balance, and otherwise subtracts it and returns true;
    • getBalance(): Double, the only way to read the balance.

    The driver starts with 100, deposits 50 and withdraws 30, which leaves 120. A withdrawal of 200 is refused. A deposit of -20, a deposit of 0 and a withdrawal of -5 are all ignored. Withdrawing 120 succeeds and empties the account, and one more withdrawal is rejected. The output:

    Balance: 120
    Balance: 120
    Withdrew all
    Balance: 0
    Rejected
    

    Approach

    The balance lives in a private var inside the class. Because it is private, a line such as account.balance = 1000000.0 in the driver does not compile: the compiler says it cannot access the property because it is private in BankAccount. The only paths to the number go through the three methods, and each method checks the rules before touching it.

    Both changing methods follow the same pattern: a guard at the top rejects bad input, and the real work happens below it. That keeps each method short and keeps the valid path easy to read.

    Step by step

    1. Declare the class with initialBalance in its header. This is the primary constructor.
    2. Store the balance. The constructor parameter exists only while the object is being set up, so a property copies it: private var balance: Double = initialBalance. It is a var because deposits and withdrawals change it, and private hides it.
    3. Start deposit. It takes a Double amount and returns nothing, so it has no return type.
    4. Guard it. If the amount is zero or less, return immediately. The balance stays as it was.
    5. Add the amount. Only a positive amount gets past the guard.
    6. Start withdraw, which returns a Boolean so the caller learns whether the money left.
    7. Refuse bad requests. One if covers both cases: the amount is not positive, or it is larger than the balance. Either one returns false.
    8. Subtract the amount from the balance.
    9. Return true. Reaching this line means the guard did not fire.
    10. Add getBalance with no parameters and a Double result, and return balance.

    The solution in Kotlin

    class BankAccount(initialBalance: Double) {
        private var balance: Double = initialBalance
    
        fun deposit(amount: Double) {
            if (amount <= 0) return
            balance += amount
        }
    
        fun withdraw(amount: Double): Boolean {
            if (amount <= 0 || amount > balance) return false
            balance -= amount
            return true
        }
    
        fun getBalance(): Double {
            return balance
        }
    }
    
    class Solution {
        fun mainFunction() {
            val account = BankAccount(100.0)
            account.deposit(50.0)
            account.withdraw(30.0)
            account.withdraw(200.0)
            println("Balance: " + account.getBalance().toInt())
            account.deposit(-20.0)
            account.deposit(0.0)
            account.withdraw(-5.0)
            println("Balance: " + account.getBalance().toInt())
            if (account.withdraw(120.0)) {
                println("Withdrew all")
            }
            println("Balance: " + account.getBalance().toInt())
            if (!account.withdraw(1.0)) {
                println("Rejected")
            }
        }
    }
    

    Some details of this Kotlin code deserve a closer look.

    Doubles and the literals

    The amounts are Double, so the driver writes 100.0, not 100. Kotlin does not convert an Int to a Double on its own. The call BankAccount(100) is a type error.

    A Double prints with a decimal point: BankAccount(10.5).getBalance() prints 10.5 and a balance of 120 would print 120.0. That is why the driver calls .toInt(), which drops the fractional part, before printing.

    The early return

    if (amount <= 0) return works in a function that returns nothing: a bare return leaves it. In withdraw, the same one-line form returns a value, return false, and the compiler checks that every path ends with a Boolean.

    Short-circuit evaluation

    In amount <= 0 || amount > balance, the second test runs only when the first is false. Either order gives the right answer here, but the guard reads naturally from "is the request even valid" to "can we afford it".

    Why a method and not a public property

    If balance were public, any code could set it to a negative number and no rule would hold. With the private property and the methods, the invariant "the balance is never negative" can only be broken inside the class, and the class never breaks it.

    Edge cases and common mistakes

    • Withdrawing the exact balance. The test is amount > balance, not >=. Withdrawing 120 from 120 succeeds and leaves 0. With >=, the "Withdrew all" line would never print.
    • Zero and negative amounts. withdraw(0.0) returns false, and so does withdraw(-5.0). A missing guard would let a negative withdrawal increase the balance.
    • Just over the balance. On an account with 100.0, withdraw(100.01) returns false and withdraw(100.0) then returns true.
    • Forgetting the guard in deposit. A deposit of -20 would quietly lower the balance.
    • Returning true too early. Subtract first, then return true, or the balance never changes.

    Key takeaways

    • A private var keeps outside code away from the data; methods are the only way in.
    • Each method validates its input in a guard, then changes the state.
    • A Boolean result tells the caller whether a request was accepted.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free