OOP Studio Ages 9-15
Encapsulation
Students keep important data inside an object and use methods to change it safely.
Keep data protected with rules.
Encapsulation keeps an object's important data inside it. Other code asks methods such as takeDamage() or heal() to make safe changes.
Nova's locked toolbox.
You do not reach inside Nova's toolbox and rearrange sharp tools. You use its handle and drawers. Methods are the safe controls; private data stays protected inside.
Whenever values need limits.
Games protect health and energy. Banks protect balances. Accounts protect passwords. One method keeps the same rules working everywhere.
Use methods instead of touching the data.
class Builder {
#energy = 6;
takeDamage(amount) {
this.#energy = Math.max(0,
this.#energy - amount);
}
heal(amount) {
this.#energy = Math.min(10,
this.#energy + amount);
}
}
Test damage ruleTest healing ruleBlock direct access
The methods guard Nova's energy.
ENERGY VAULT IMAGEFuture protected-energy or toolbox artwork
LOCKED DATA
Nova's energy
6 / 10
Test all three controls to see what encapsulation protects.
Encapsulation complete!
Nova's methods changed energy safely, and direct access to private data was blocked.
Completed! Open Encapsulation Builder