Start learning free

LESSON 64 OF 69 · PROJECTS: OBJECT-ORIENTED

Bank Account in Java: 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. Mark the balance field private double balance, so only the methods of BankAccount can touch it.

What the class must have (Java):

  • public BankAccount(double initialBalance): creates an account that starts with the given balance.
  • public void deposit(double amount): adds amount to the balance. If amount is zero or negative, do nothing (no error, the balance stays the same).
  • public boolean withdraw(double amount): 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).
  • public double getBalance(): returns the current balance. It is the only way for outside code to read it.

The starter prints the balance with (int)account.getBalance(): the (int) cast drops the .0 so the output is Balance: 120, not Balance: 120.0.

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

class Solution {
    public void mainFunction() {
        BankAccount account = new BankAccount(100);
        account.deposit(50);
        account.withdraw(30);
        account.withdraw(200);
        System.out.println("Balance: " + (int)account.getBalance());
        account.deposit(-20);
        account.deposit(0);
        account.withdraw(-5);
        System.out.println("Balance: " + (int)account.getBalance());
        if (account.withdraw(120)) {
            System.out.println("Withdrew all");
        }
        System.out.println("Balance: " + (int)account.getBalance());
        if (!account.withdraw(1)) {
            System.out.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 double balance;, then in the constructor balance = initialBalance;.

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

class BankAccount {
    private double balance;

    public BankAccount(double initialBalance) {
        balance = initialBalance;
    }

    public void deposit(double amount) {
        if (amount <= 0) return;
        balance += amount;
    }

    public boolean withdraw(double amount) {
        if (amount <= 0 || amount > balance) return false;
        balance -= amount;
        return true;
    }

    public double getBalance() {
        return balance;
    }
}

class Solution {
    public void mainFunction() {
        BankAccount account = new BankAccount(100);
        account.deposit(50);
        account.withdraw(30);
        account.withdraw(200);
        System.out.println("Balance: " + (int)account.getBalance());
        account.deposit(-20);
        account.deposit(0);
        account.withdraw(-5);
        System.out.println("Balance: " + (int)account.getBalance());
        if (account.withdraw(120)) {
            System.out.println("Withdrew all");
        }
        System.out.println("Balance: " + (int)account.getBalance());
        if (!account.withdraw(1)) {
            System.out.println("Rejected");
        }
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    JAVA · PROJECTS: OBJECT-ORIENTED

    Bank Account in Java, explained

    Problem overview

    The task is to build a BankAccount class that keeps its balance in a private double field. Outside code can't read or write that field. It has to go through four members:

    • BankAccount(double initialBalance) creates an account with a starting balance.
    • deposit(double amount) adds money, and does nothing when amount is zero or negative.
    • withdraw(double amount) removes money and returns true. It returns false and changes nothing when amount is zero or negative, or larger than the balance. Withdrawing exactly the whole balance is allowed.
    • getBalance() returns the current balance.

    The driver starts at 100, deposits 50, withdraws 30 and then tries to withdraw 200, which is refused. The balance is 120. It then tries deposit(-20), deposit(0) and withdraw(-5), all ignored, and prints 120 again. Withdrawing 120 succeeds and leaves 0, and withdrawing 1 more is refused:

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

    Approach: let the object guard its own data

    This is encapsulation. If balance were a public field, any code could write account.balance = -1000 and break the account. Because the field is private, only the methods of BankAccount can touch it, and those methods are the one place where the rules are checked. Every rule becomes a guard: a check at the top of a method that leaves early when the request is invalid, so the code that changes the balance runs only for valid amounts.

    Two guards are needed. deposit rejects amount <= 0. withdraw rejects amount <= 0 and also amount > balance. The comparison with the balance is strict, so an amount equal to the balance gets through and empties the account.

    The two methods answer differently. deposit returns void because ignoring a bad amount is silent. withdraw returns a boolean so the caller can tell whether the money left, which is how the driver prints Withdrew all and Rejected.

    Reading the driver against the guards: withdraw(200) fails the amount > balance test because 200 is more than 150 minus 30. deposit(-20), deposit(0) and withdraw(-5) all fail the amount <= 0 test. withdraw(120) passes both tests, because 120 is not more than 120, so the balance becomes 0. The final withdraw(1) then fails the comparison with the balance, and the driver prints Rejected.

    Step by step

    1. Declare the class BankAccount, above the driver. Everything about the account lives inside it.
    2. Add the private field double balance. This is the hidden state.
    3. Write the constructor. It is public, has the class's name and no return type, and takes initialBalance.
    4. Store the starting value: assign initialBalance to balance.
    5. Start deposit: public, void, with a double amount parameter.
    6. Guard it. A one-line if (amount <= 0) return; leaves at once for a bad amount.
    7. Add the amount to balance below the guard.
    8. Start withdraw: public, returning boolean, with a double amount parameter.
    9. Guard it with both refusals in one condition, returning false.
    10. Subtract the amount from balance.
    11. Return true: reaching this line means the withdrawal happened.
    12. Add the getter getBalance, public, returning double, with no parameters.
    13. Return balance from it. This is the only way outside code can read the value.

    The solution in Java

    class BankAccount {
        private double balance;
    
        public BankAccount(double initialBalance) {
            balance = initialBalance;
        }
    
        public void deposit(double amount) {
            if (amount <= 0) return;
            balance += amount;
        }
    
        public boolean withdraw(double amount) {
            if (amount <= 0 || amount > balance) return false;
            balance -= amount;
            return true;
        }
    
        public double getBalance() {
            return balance;
        }
    }
    
    class Solution {
        public void mainFunction() {
            BankAccount account = new BankAccount(100);
            account.deposit(50);
            account.withdraw(30);
            account.withdraw(200);
            System.out.println("Balance: " + (int)account.getBalance());
            account.deposit(-20);
            account.deposit(0);
            account.withdraw(-5);
            System.out.println("Balance: " + (int)account.getBalance());
            if (account.withdraw(120)) {
                System.out.println("Withdrew all");
            }
            System.out.println("Balance: " + (int)account.getBalance());
            if (!account.withdraw(1)) {
                System.out.println("Rejected");
            }
        }
    }
    

    Java details worth knowing:

    • private is per class, not per object. Code outside BankAccount, such as Solution, can't write account.balance; the compiler rejects it. Only the class's own methods can.
    • A guard with return; in a void method. It exits the method without a value. In withdraw the guard returns false instead, because the method must return a boolean on every path.
    • || short-circuits. In amount <= 0 || amount > balance, the second comparison is evaluated only when the first is false. Either one being true is enough to refuse.
    • The (int) cast in the driver only affects printing. (int)account.getBalance() drops the fractional part, which is why the output reads Balance: 120 and not Balance: 120.0. It truncates rather than rounds: an account holding 120.75 prints 120 through the cast, while getBalance() returns 120.75.
    • The constructor and field share no name here. The parameter is initialBalance, so balance = initialBalance; needs no this..

    Edge cases and common mistakes

    • Using amount >= balance. That would refuse the withdrawal of exactly 120 from a balance of 120, and the driver would never print Withdrew all.
    • Forgetting the amount <= 0 check in withdraw. A call like withdraw(-5) would pass the amount > balance test and then subtract a negative number, which adds money.
    • Changing the balance before checking. The guards come first, so a refused request never touches the state.
    • Returning nothing from withdraw. The driver uses the result in if (account.withdraw(120)), so it has to be a boolean.
    • Floating-point rounding. double can't store most decimal fractions exactly. Depositing 0.1 three times into an empty account makes getBalance() return 0.30000000000000004. The lesson's amounts are whole numbers, so the tests don't run into this.
    • NaN. Every comparison with NaN is false, so amount <= 0 doesn't catch it. deposit(Double.NaN) on an account holding 50 leaves the balance as NaN. The lesson's tests never pass it.

    Testing

    • A new account with 10: withdraw(10.0001) returns false, then withdraw(10) returns true and getBalance() returns 0.0.
    • An account with 120.75: (int)account.getBalance() gives 120, and getBalance() itself gives 120.75.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free