Learn Java · lesson 41 of 61 · about 10 minutes
Project: Bank Account
Open the loyalty account: model an account with safe earning and spending and a history of changes.
What you'll learn
- Design a class with private state
- Reject invalid operations
- Keep a history in a list
The loyalty account
The cinema's loyalty scheme works like a small bank account, counted in points instead of money. A Loyalty account in the customer's name earns tonight's points first, then the customer can earn more or redeem some, until done. Points can't go below 0, so redeem() refuses more than there is, and neither method accepts an amount that isn't above 0. Each one returns whether it happened, so the desk can say Refused: redeem 500, and every change goes into a history list for the statement, like Ada: +89 -50 +20 -30 = 29.
The design
Account keeps the owner, the balance in pence and a history list, all private.
depositandwithdrawreturn true if they workedgetBalance()andstatement()only read
Step 1: private state, a method that checks first
class Jar {
private int sweets = 0;
boolean put(int n) {
if (n <= 0) return false;
sweets += n;
return true;
}
int getSweets() {
return sweets;
}
}
public class Main {
public static void main(String[] args) {
Jar j = new Jar();
System.out.println(j.put(5) + " " + j.put(-1) + " " + j.getSweets());
}
}
Output
true false 5The history
Each successful change adds a line like +5000 to a private List<String>, and statement() joins them. The owner is final: an account never changes hands.
The account
import java.util.ArrayList;
import java.util.List;
class Account {
private final String owner;
private int balance = 0;
private final List<String> history = new ArrayList<>();
Account(String owner) {
this.owner = owner;
}
boolean deposit(int pence) {
if (pence <= 0) return false;
balance += pence;
history.add("+" + pence);
return true;
}
boolean withdraw(int pence) {
if (pence <= 0 || pence > balance) return false;
balance -= pence;
history.add("-" + pence);
return true;
}
int getBalance() {
return balance;
}
String statement() {
return owner + ": " + String.join(" ", history) + " = " + balance;
}
}
public class Main {
public static void main(String[] args) {
Account acc = new Account("Ada");
acc.deposit(5000);
acc.withdraw(2000);
System.out.println(acc.withdraw(9000) + " " + acc.deposit(-5));
System.out.println(acc.statement());
}
}Output
false false
Ada: +5000 -2000 = 3000Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.