Skip to content

Java OOP

0/36 lessons · 0% complete

— XP

Java OOP · Module 13

Stage 1 — Customer, Account and safe money

Classes, constructors, encapsulation and validation working together

30m60 XP
→→→

What you'll be able to do

  • See the whole system before writing any of it
  • Give each class exactly one responsibility
  • Protect money with private fields plus validating methods
  • Make rejected operations leave the object completely unchanged
1

Project — Accounts & Encapsulation

The plan, then the foundation

You now know every concept this system needs. The only new skill in Module 13 is deciding *which* concept to use where.

The four stages

StageWhat you addConcepts exercised
1. FoundationCustomer, Account with validated deposit/withdrawclasses, constructors, encapsulation, validation, composition
2. Hierarchyabstract Account → SavingsAccount, CurrentAccountabstract classes, inheritance, super, overriding, polymorphism
3. TransactionsTransactable contract + Transaction historyinterfaces, composition, arrays, encapsulation
4. BankBank that owns the accounts and reportsaggregation, polymorphic loops, lookups, abstraction

Each stage is a complete, runnable program judged by its own hidden tests — you never have to keep four stages working at once.

Step 1: give every class one job

Before typing, write the responsibilities down. This is the design step professionals do on paper: | Class | Knows | Does | Never does | | --- | --- | --- | --- | | Customer | a name | expose it through a getter | nothing about money | | Account | id, owner, balance | deposit, withdraw, statement | print the customer's internals | Two design decisions follow immediately: 1. Account HAS-A Customer (a field), because an account is not a kind of customer — the Module 12 test. 2. balance is private, because Module 4 showed what happens when money is a public field: account.balance = -5000; compiles and destroys your data.

Step 2: the rules money must obey

  1. A deposit must be positive — otherwise print Invalid amount and change nothing.
  2. A withdrawal must be positive and available — otherwise print Insufficient funds, return false, and change nothing.
  3. A successful withdrawal returns true, so the caller can react to the outcome.
  4. Validation lives *inside* the class. If callers had to check first, one forgetful caller would corrupt the balance.
The same shape, a different domain

Study this wallet, then build the bank version yourself in the challenge below. Try `wallet.add(-10.0);` — the guard prints and returns before touching the amount.

Output
Press Run to execute this example.

Why the guard is written this way

Main.java
1public boolean take(double value) {
2 if (value <= 0 || value > amount) {
3 System.out.println("Insufficient funds");
4 return false;
5 }
6 amount = amount - value;
7 return true;
8}
if (value <= 0 || value > amount) {
Both bad cases in one guard: a non-positive request and a request larger than the balance. Checking *before* mutating is the whole point.
return false;
Leaving the method early guarantees the balance is untouched. There is no path where the message prints *and* the money moves.
amount = amount - value;
Reached only when the request is valid — the 'happy path' sits at the end, unindented and easy to read.
return true;
A boolean result lets the caller branch: if (account.withdraw(100)) { printReceipt(); }. A void method would throw that information away.

Read the expected output like a specification

The challenge expects Insufficient funds and then ACC-1 | Sara | 650.0. That single line tells you: the rejected withdrawal printed nothing else, the successful ones did not print at all, and statement() uses | as the separator with the balance formatted as a double. Matching the specification exactly is part of the job.

Prove it — coding challenges

Common mistakes

WrongPrinting `Insufficient funds` and then subtracting anyway.
WhyA hidden test checks the balance after a rejected withdrawal — the message alone is not enough.
Fix`return false;` inside the guard so the mutation is unreachable.
WrongStoring the owner's name in `Account` as a `String`.
WhyThe customer becomes duplicated data; changing the name in one place leaves the other stale.
FixHold a `Customer` object and ask it: `owner.getName()`.
WrongMaking `balance` public 'just for the statement'.
WhyThe concept layer requires `private` money — and any caller could then set it directly.
FixKeep the field private and add `getBalance()`.

Lesson playground

Free practice

A rejected deposit must not move the total *or* the counter. Add a `withdraw` with the same discipline and check that a rejected withdrawal leaves both untouched.

Output
Press Run to execute this example.

Check understanding

Quiz

Question 1 of 3

Two withdrawals, one of them impossible. What is printed?

Main.java
1class Purse {
2 private double balance;
3
4 Purse(double opening) {
5 this.balance = opening;
6 }
7
8 public boolean withdraw(double amount) {
9 if (amount <= 0 || amount > balance) {
10 System.out.println("Insufficient funds");
11 return false;
12 }
13 balance = balance - amount;
14 return true;
15 }
16
17 public double getBalance() {
18 return balance;
19 }
20}
21
22public class Main {
23 public static void main(String[] args) {
24 Purse purse = new Purse(100.0);
25
26 System.out.println(purse.withdraw(30.0));
27 System.out.println(purse.withdraw(500.0));
28 System.out.println(purse.getBalance());
29 }
30}

Summary

  • Design first: one responsibility per class, written down before any code.
  • `Account` HAS-A `Customer`; money is private and reached only through methods.
  • Guard, print, return — a rejected operation must leave the object exactly as it was.
  • Return `boolean` from operations that can fail so callers can react.