Back to Encapsulation Builder
Encapsulation Challenge

Safe Savings Mission

Protect a piggy bank's private balance. Only its methods may add or remove coins, and every method must enforce a rule.

GoalSave safelyReject overspendingProtect #balance
The rule:#balance stays inside the piggy bank. Outside code must ask deposit() or spend() to change it.
Challenge Controls

Run each command in order.

class PiggyBank {
  #balance = 0;

  deposit(coins) { /* add safely */ }
  spend(coins) { /* check first */ }
}

COMMAND TERMINAL
// Select the first method below.
Protected Piggy Bank

First, deposit 5 coins.

Coins dropping An empty piggy bank
PRIVATE #balance0 coins
Methods guard the coin slot.
DepositSafe spendReject overspendBlock access

The balance starts at zero and cannot be edited directly.