Back to Polymorphism Challenge
OOP Studio Ages 9-15

Encapsulation

Students keep important data inside an object and use methods to change it safely.

15-20 min Ages 9-15 OOP JavaScript
What Is It?

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.

Metaphor

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.

When Is It Used?

Whenever values need limits.

Games protect health and energy. Banks protect balances. Accounts protect passwords. One method keeps the same rules working everywhere.

Nova's Protected Energy

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
Protected Object

The methods guard Nova's energy.

Nova the builder
ENERGY VAULT IMAGEFuture protected-energy or toolbox artwork
LOCKED DATA
Nova's energy
6 / 10
Only methods may open the energy controls.

Test all three controls to see what encapsulation protects.