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.
The rule:
#balance stays inside the piggy bank. Outside code must ask deposit() or spend() to change it.Run each command in order.
class PiggyBank {
#balance = 0;
deposit(coins) { /* add safely */ }
spend(coins) { /* check first */ }
}
COMMAND TERMINAL
// Select the first method below.
First, deposit 5 coins.
PRIVATE #balance0 coins
Methods guard the coin slot.
DepositSafe spendReject overspendBlock access
The balance starts at zero and cannot be edited directly.
Encapsulation challenge complete!
The piggy bank protected its balance and enforced every savings rule.
Finish Encapsulation Challenge