These are the notes for Java episode 25, a project episode. Over episodes 14 to 24 you learned classes and objects, constructors, static, encapsulation, inheritance, polymorphism, abstract classes, interfaces, final, the Object class, nested classes, enums and records. Today you use all of them together to build a small bank for Sharma ji's cooperative: requirements first, then a class map, then accounts that protect their own money, an all-or-nothing transfer (and the bug that creates money out of thin air), a passbook made of records, automatic account numbers, and monthly interest through an interface. Every example was run with javac 21.
The problem: Sharma ji's ledger
Sharma ji runs a cooperative bank with 300 members. Every rupee is written by hand in a ledger; month-end interest takes two days, and last month someone withdrew more than they had without anyone noticing. The obvious first program:
class Account {
String name;
double balance;
}
public class Main {
public static void main(String[] args) {
Account a = new Account();
a.name = "Sharma ji";
a.balance = 10000;
a.balance = a.balance - 15000; // withdraw 15000
a.balance = a.balance + -2000; // "deposit" -2000
System.out.println(a.name + ": " + a.balance);
}
}
Sharma ji: -7000.0
The program withdrew more than he had and accepted a negative "deposit" (a hidden withdrawal). Why it fails: the data has no rules attached. Any line of code anywhere can set any balance to anything.
Step 0: requirements
Real projects start with requirements, not code:
| # | Requirement | Details |
|---|---|---|
| 1 | Open accounts | savings (SB...) and current (CA...), numbers given automatically |
| 2 | Deposit / withdraw with rules | no zero or negative amounts; savings keeps a minimum of 1,000; current may go to -5,000 (an overdraft) |
| 3 | Transfer | all or nothing: money is never created or lost |
| 4 | Passbook | every transaction with the balance after it |
| 5 | Monthly interest | 0.5% a month (6% a year), only for savings |
| 6 | Report | every account and the total money held |
Step 1: design like a bank branch
| In a bank branch | In our program | OOP idea |
|---|---|---|
| A passbook only the cashier may write in | abstract class Account with a private balance and rules in its methods |
encapsulation, abstraction |
| Savings vs current: same counter, different limits | SavingsAccount, CurrentAccount override minBalance() |
inheritance, polymorphism |
| A passbook entry, printed once, never edited | record Txn + enum Type |
records, enums |
| A customer's ID details | record Customer(String name, String phone) |
records |
| Only savings earns interest | interface InterestBearing |
interfaces |
| The branch manager: opens, finds, moves money | class Bank |
composition (a bank has accounts) |
Class map:
Bank ── has many ──> Account (abstract: number, owner, private balance, history)
├── SavingsAccount (minBalance 1000, implements InterestBearing)
└── CurrentAccount (minBalance -5000)
Account ── has many ──> Txn (record: Type, amount, balanceAfter)
Account ── has one ───> Customer (record: name, phone)
Each class has one job. That's what keeps the code easy to change.
Step 2: accounts that protect themselves
abstract class Account {
private final String number;
private double balance;
Account(String number, double opening) {
this.number = number;
balance = opening;
}
abstract double minBalance();
final boolean withdraw(double amount) {
if (amount <= 0 || balance - amount < minBalance())
return false;
balance -= amount;
return true;
}
boolean deposit(double amount) {
if (amount <= 0) return false;
balance += amount;
return true;
}
public String toString() { return number + ": " + balance; }
}
class Savings extends Account {
Savings(String n, double o) { super(n, o); }
double minBalance() { return 1000; }
}
class Current extends Account {
Current(String n, double o) { super(n, o); }
double minBalance() { return -5000; }
}
public class Main {
public static void main(String[] args) {
Account[] all = { new Savings("SB1001", 10000),
new Current("CA2001", 10000) };
for (Account a : all)
System.out.println(a.withdraw(12000) + " -> " + a);
System.out.println("Deposit -500: " + all[0].deposit(-500));
}
}
false -> SB1001: 10000.0
true -> CA2001: -2000.0
Deposit -500: false
Accountis abstract: there's no "plain" account at the counter.balanceis private: the only way to change it is throughdepositandwithdraw, which check the rules.minBalance()is abstract: every child must state its limit.withdrawis final (episode 22): children choose the limit, but no child can skip the check.- Polymorphism: the same call
a.withdraw(12000)applies the savings rule to one object and the current rule to the other.
Step 3: the transfer bug
A first transfer deposits first, then withdraws (a simpler Account here, to focus on the transfer):
class Account {
final String number;
private double balance;
Account(String number, double balance) {
this.number = number;
this.balance = balance;
}
boolean withdraw(double amount) {
if (amount <= 0 || amount > balance) return false;
balance -= amount;
return true;
}
boolean deposit(double amount) {
if (amount <= 0) return false;
balance += amount;
return true;
}
double getBalance() { return balance; }
public String toString() { return number + "=" + balance; }
}
class Bank {
static boolean transfer(Account from, Account to, double amt) {
to.deposit(amt);
return from.withdraw(amt);
}
}
public class Main {
public static void main(String[] args) {
Account asha = new Account("SB1001", 10000);
Account ravi = new Account("SB1002", 10000);
boolean ok = Bank.transfer(asha, ravi, 20000);
System.out.println("Transfer: " + ok);
System.out.println(asha + " " + ravi);
double total = asha.getBalance() + ravi.getBalance();
System.out.println("Bank total: " + total);
}
}
Transfer: false
SB1001=10000.0 SB1002=30000.0
Bank total: 40000.0
The transfer "failed", yet Ravi gained 20,000 and the bank's total doubled. Why: the steps were in the wrong order and nobody checked the first result. A transfer must be all or nothing (databases call this a transaction, and the property atomicity). Fix: withdraw first, and only deposit if it succeeded:
static boolean transfer(Account from, Account to, double amt) {
if (!from.withdraw(amt)) return false;
to.deposit(amt);
return true;
}
Transfer: false
SB1001=10000.0 SB1002=10000.0
Bank total: 20000.0
A useful habit: write an invariant (something that must always be true, here "total money is unchanged by a transfer") and print it after every operation while testing.
Step 4: a passbook and automatic account numbers
enum Type { DEPOSIT, WITHDRAW }
record Txn(Type type, double amount, double balanceAfter) { }
class Account {
private static int next = 1001;
final String number = "SB" + next++;
private double balance;
private final Txn[] history = new Txn[100];
private int count = 0;
boolean deposit(double amount) {
if (amount <= 0) return false;
balance += amount;
history[count++] = new Txn(Type.DEPOSIT, amount, balance);
return true;
}
boolean withdraw(double amount) {
if (amount <= 0 || amount > balance) return false;
balance -= amount;
history[count++] = new Txn(Type.WITHDRAW, amount, balance);
return true;
}
void statement() {
System.out.println("Statement for " + number);
for (int i = 0; i < count; i++)
System.out.println(" " + history[i]);
}
}
public class Main {
public static void main(String[] args) {
Account asha = new Account();
Account ravi = new Account();
asha.deposit(5000);
asha.withdraw(1200);
asha.withdraw(99999);
ravi.deposit(700);
asha.statement();
ravi.statement();
}
}
Statement for SB1001
Txn[type=DEPOSIT, amount=5000.0, balanceAfter=5000.0]
Txn[type=WITHDRAW, amount=1200.0, balanceAfter=3800.0]
Statement for SB1002
Txn[type=DEPOSIT, amount=700.0, balanceAfter=700.0]
private static int next = 1001;is shared by all accounts (episode 16); each new account takesnext++, so numbers never repeat and are never typed by hand.- Each passbook entry is a
record Txn(immutable, prints itself) with anenum Type. - The refused 99,999 withdrawal left no entry, because nothing happened.
- A fixed array of 100 is a limit; in episode 30,
ArrayListgrows automatically.
Step 5: monthly interest through an interface
Only savings accounts earn interest. "Something only some classes can do" is a capability, so it's an interface (episode 21). The first try adds interest straight to the balance inside SavingsAccount:
class Savings extends Account {
Savings(double o) { super(o); }
double minBalance() { return 1000; }
void addInterest() { balance += balance * 0.005; }
}
Main.java:9: error: balance has private access in Account
void addInterest() { balance += balance * 0.005; }
^
Even a child class can't touch its parent's private field, and that's good: interest goes through deposit, so it is checked and written in the passbook like everything else. The bank then asks each account whether it has the capability:
if (accounts[i] instanceof InterestBearing ib)
ib.addMonthlyInterest();
instanceof with a variable name (pattern matching, Java 16+) checks the type and casts in one step.
The full program
enum Type { DEPOSIT, WITHDRAW, INTEREST, TRANSFER_IN, TRANSFER_OUT }
record Txn(Type type, double amount, double balanceAfter) { }
record Customer(String name, String phone) { }
interface InterestBearing {
void addMonthlyInterest();
}
abstract class Account {
private static int next = 1001;
private final String number;
private final Customer owner;
private double balance;
private final Txn[] history = new Txn[100];
private int count = 0;
Account(String prefix, Customer owner, double opening) {
this.number = prefix + next++;
this.owner = owner;
this.balance = opening;
}
abstract double minBalance();
final boolean withdraw(double amount, Type type) {
if (amount <= 0 || balance - amount < minBalance())
return false;
balance -= amount;
log(type, amount);
return true;
}
final boolean deposit(double amount, Type type) {
if (amount <= 0) return false;
balance += amount;
log(type, amount);
return true;
}
private void log(Type type, double amount) {
if (count < history.length)
history[count++] = new Txn(type, amount, balance);
}
double getBalance() { return balance; }
String getNumber() { return number; }
Customer getOwner() { return owner; }
void printStatement() {
System.out.println("Statement " + number + ", " + owner.name());
for (int i = 0; i < count; i++) {
Txn t = history[i];
System.out.printf(" %-12s %9.2f balance %9.2f%n",
t.type(), t.amount(), t.balanceAfter());
}
}
@Override
public String toString() {
return number + " " + owner.name() + ": " + balance;
}
}
class SavingsAccount extends Account implements InterestBearing {
static final double MONTHLY_RATE = 0.005; // 6% a year
SavingsAccount(Customer owner, double opening) {
super("SB", owner, opening);
}
double minBalance() { return 1000; }
public void addMonthlyInterest() {
deposit(getBalance() * MONTHLY_RATE, Type.INTEREST);
}
}
class CurrentAccount extends Account {
CurrentAccount(Customer owner, double opening) {
super("CA", owner, opening);
}
double minBalance() { return -5000; } // overdraft limit
}
class Bank {
private final Account[] accounts = new Account[50];
private int size = 0;
Account open(Account a) {
accounts[size++] = a;
return a;
}
Account find(String number) {
for (int i = 0; i < size; i++)
if (accounts[i].getNumber().equals(number))
return accounts[i];
return null;
}
boolean transfer(String fromNo, String toNo, double amount) {
Account from = find(fromNo), to = find(toNo);
if (from == null || to == null || from == to) return false;
if (!from.withdraw(amount, Type.TRANSFER_OUT)) return false;
to.deposit(amount, Type.TRANSFER_IN);
return true;
}
void monthEnd() {
for (int i = 0; i < size; i++)
if (accounts[i] instanceof InterestBearing ib)
ib.addMonthlyInterest();
}
double totalMoney() {
double t = 0;
for (int i = 0; i < size; i++) t += accounts[i].getBalance();
return t;
}
void report() {
for (int i = 0; i < size; i++)
System.out.println(accounts[i]);
System.out.println("Total money in bank: " + totalMoney());
}
}
public class Main {
public static void main(String[] args) {
Bank bank = new Bank();
Customer c1 = new Customer("Asha", "9876543210");
Customer c2 = new Customer("Ravi", "9123456780");
Account asha = bank.open(new SavingsAccount(c1, 10000));
Account ravi = bank.open(new CurrentAccount(c2, 2000));
boolean w1 = asha.withdraw(9500, Type.WITHDRAW);
boolean w2 = ravi.withdraw(6000, Type.WITHDRAW);
boolean t1 = bank.transfer("SB1001", "CA1002", 3000);
boolean t2 = bank.transfer("SB1001", "CA1002", 50000);
System.out.println("Savings withdraw 9500: " + w1);
System.out.println("Current withdraw 6000: " + w2);
System.out.println("Transfer 3000: " + t1);
System.out.println("Transfer 50000: " + t2);
bank.monthEnd();
bank.report();
asha.printStatement();
ravi.printStatement();
}
}
Savings withdraw 9500: false
Current withdraw 6000: true
Transfer 3000: true
Transfer 50000: false
SB1001 Asha: 7035.0
CA1002 Ravi: -1000.0
Total money in bank: 6035.0
Statement SB1001, Asha
TRANSFER_OUT 3000.00 balance 7000.00
INTEREST 35.00 balance 7035.00
Statement CA1002, Ravi
WITHDRAW 6000.00 balance -4000.00
TRANSFER_IN 3000.00 balance -1000.00
Reading the output:
- Savings refused 9,500 (10,000 - 9,500 = 500, below its 1,000 minimum).
- Current allowed 6,000 (2,000 - 6,000 = -4,000, inside the -5,000 overdraft).
- The 3,000 transfer worked; the 50,000 transfer was refused and changed nothing.
- Month end: Asha earned 0.5% of 7,000 = 35; Ravi's current account was skipped.
mainreads like a story, because every rule lives inside the class it belongs to.
Where each OOP idea appears
| Idea | Episode | In the bank |
|---|---|---|
| Classes and objects | 14 | Bank, Account objects |
Constructors, super |
15, 18 | SavingsAccount(...) { super("SB", owner, opening); } |
static |
16 | next account number, MONTHLY_RATE constant |
| Encapsulation | 17 | private double balance |
| Inheritance | 18 | SavingsAccount extends Account |
| Polymorphism | 19 | minBalance() chosen at runtime |
| Abstract classes | 20 | abstract class Account, abstract double minBalance() |
| Interfaces | 21 | InterestBearing |
final, toString |
22 | final boolean withdraw, toString() |
| Records, enums | 24 | Txn, Customer, Type |
Common mistakes (and the real error messages)
| Mistake | Real message | Why | Fix |
|---|---|---|---|
| Child doesn't implement the abstract method | error: Savings is not abstract and does not override abstract method minBalance() in Account |
every concrete child must give its limit | add double minBalance() { return 1000; } |
Child has no constructor calling super(...) |
error: constructor Account in class Account cannot be applied to given types; / required: double / found: no arguments |
Account has no empty constructor | Savings(double o) { super(o); } |
| Child touches the parent's private field | error: balance has private access in Account |
private is private, even for children | go through deposit(...) |
| Passbook array overflows | ArrayIndexOutOfBoundsException: Index 100 out of bounds for length 100 |
the array is full | check count < history.length (or use ArrayList, episode 30) |
| Deposit before checking the withdrawal | no error; money is created | wrong order, unchecked result | withdraw first, deposit only on success |
Practice
- Add a
FixedDepositAccountthat never allows withdrawals. Can you do it without changingAccount? - Add a daily withdrawal limit of 2,000 for savings accounts. Where should that rule live?
- Print the top 3 accounts by balance.
- Add a
Scannermenu:1deposit,2withdraw,3transfer,4report,0exit.
Solutions
1. Yes. withdraw is final, but it asks minBalance(). Return something no balance can satisfy:
class FixedDepositAccount extends Account {
FixedDepositAccount(Customer owner, double opening) {
super("FD", owner, opening);
}
double minBalance() { return Double.MAX_VALUE; } // every withdrawal is refused
}
balance - amount < Double.MAX_VALUE is always true, so withdraw always returns false. (A cleaner design adds an overridable canWithdraw(amount) hook to Account.)
2. In SavingsAccount, because it's a savings rule. Since withdraw is final, add a hook in Account that withdraw calls (for example boolean allowed(double amount), returning true by default), and override it in SavingsAccount to track today's total.
3. Copy the accounts into an array of size size, sort it by balance (a simple selection sort from the basics, or Arrays.sort with a Comparator, episode 34), and print the first three.
4. A while (true) loop that reads a choice with Scanner (episode 4) and a switch that calls bank.find(...), deposit, withdraw, transfer or report; 0 breaks the loop.
Quick quiz
// minBalance(): Savings 1000, Current -5000
Account s = new SavingsAccount(c1, 3000);
Account k = new CurrentAccount(c2, 3000);
boolean a = s.withdraw(2500, Type.WITHDRAW);
boolean b = k.withdraw(2500, Type.WITHDRAW);
System.out.println(a + " " + b);
A) true true B) false true C) true false D) false false
Answer
B. Savings would drop to 500, below its 1,000 minimum, so it's refused. Current would be at 500, far above -5,000, so it's allowed.
false true
Interview questions
- How would you design a bank system in OOP? Start from requirements; an abstract
Accountwith a private balance and rule-checking methods, subclasses for account types, records for immutable transactions, an interface for optional capabilities like interest, and aBankthat coordinates. - Why is the balance private? So every change goes through methods that enforce the rules (encapsulation); no other code can corrupt it.
- Why make
withdrawfinal butminBalanceabstract? The process must never change (template method pattern); only the limit varies by account type. - How do you make a transfer safe? Withdraw first, deposit only on success, and roll back on any failure; in real systems, database transactions (and locks, episode 40) guarantee atomicity.
- Why are transactions records? A passbook entry must never change after it's written; records are immutable and give
toString/equalsfor free. - Interface or abstract class for interest? Interface: it's a capability only some accounts have, and a class can implement many interfaces but extend only one class.
- Why not use
doublefor money in production? Binary floating point can't represent many decimal values exactly; real banking code usesBigDecimalor stores paise aslong. - What is an invariant? A condition that must always hold, like "a transfer doesn't change the total money"; checking it catches bugs early.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Requirements | What the software must do, written before coding | "savings keeps a 1,000 minimum" |
| Class map | A sketch of the classes and how they relate | Bank → Account → Txn |
| Encapsulation | Keeping data private behind rule-checking methods | private double balance |
| Abstract class | A class that can't be instantiated; a common parent | abstract class Account |
| Abstract method | A method with no body that children must implement | abstract double minBalance() |
| Polymorphism | The same call runs different code for different objects | a.withdraw(12000) |
| Overdraft | Allowed negative balance in a current account | down to -5,000 |
| Minimum balance | The lowest balance a savings account may keep | 1,000 |
| Transfer | Moving money from one account to another | bank.transfer("SB1001", "CA1002", 3000) |
| Atomic (all or nothing) | Either every step happens or none does | a safe transfer |
| Invariant | A condition that must always stay true | total money unchanged by a transfer |
| Passbook / statement | The list of an account's transactions | printStatement() |
| Record | An immutable data class | record Txn(Type type, double amount, double balanceAfter) |
| Enum | A fixed list of values | enum Type { DEPOSIT, WITHDRAW, ... } |
| Static counter | A shared variable used to give unique numbers | private static int next = 1001; |
| Capability interface | An interface for something only some classes can do | InterestBearing |
Pattern matching instanceof |
Type check and cast in one step | a instanceof InterestBearing ib |
| Composition | An object made of other objects ("has a") | a Bank has Accounts |
| Template method | A final method whose steps call overridable methods | withdraw calls minBalance() |
Summary
- Start from requirements, then a class map where each class has one job.
- A private balance with rules inside
deposit/withdrawmeans no code can corrupt the money. - An abstract
Account, a finalwithdraw, and children overridingminBalance()give two account types with one safe process (polymorphism). - A transfer must be all or nothing: withdraw first, deposit only on success.
- A record + enum make a passbook; a static counter numbers accounts; an interface marks which accounts earn interest.
- Next: a failed transfer just says
false. Why did it fail, and what if the caller ignores it? Episode 26: exceptions: try, catch, finally, checked vs unchecked.