Build a BankAccount class

Description: Create a class BankAccount with a private balance. Add deposit(amount) and withdraw(amount). Refuse a negative deposit and a withdraw bigger than the balance (throw an exception). Test it.

Hint:

  • Keep the field private and give a getter only.
  • Throw IllegalArgumentException and IllegalStateException.

Solution

class BankAccount {
    private double balance;

    void deposit(double amount) {
        if (amount <= 0) throw new IllegalArgumentException("Deposit must be positive");
        balance += amount;
    }

    void withdraw(double amount) {
        if (amount > balance) throw new IllegalStateException("Not enough balance");
        balance -= amount;
    }

    double getBalance() { return balance; }
}

public class Main {
    public static void main(String[] args) {
        BankAccount acc = new BankAccount();
        acc.deposit(1000);
        acc.withdraw(250);
        System.out.println(acc.getBalance());

        try {
            acc.withdraw(5000);
        } catch (IllegalStateException e) {
            System.out.println("Error: " + e.getMessage());
        }
        try {
            acc.deposit(-5);
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
Output

750.0
Error: Not enough balance
Error: Deposit must be positive

How it works

  • The balance is private, so the only way to change it is through the two methods which check the values.

Read Java Encapsulation.


Learn more about the similar topics:
Tutorials
Java Classes and Objects
Java Constructors
Java static and this Keywords
Java Encapsulation and Access Modifiers
Java Inheritance
Java Polymorphism
Java Abstract Classes
Exercises & Assignments
Build a BankAccount class
Calculate areas with inheritance and polymorphism
Use a sealed interface and pattern matching
Interview Questions & Answers
What is a class and an object in Java?
What is a constructor in Java?
What is the difference between a constructor and a method in Java?
What is the this keyword in Java?
What is the static keyword in Java?
What is the final keyword in Java?
What are the four pillars of OOP in Java?