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

Encapsulation

Encapsulation puts the object's data in a protective case with rules on the door. Nobody sets the player's health directly — they ask takeDamage(), and the method enforces the rules, like "health never drops below zero."

health: 10 ❤️❤️❤️ takeDamage() 🛡️
  1. 1

    Data lives inside the case

    this.health belongs to the Player object. The rest of the program shouldn't reach in and scribble on it — that's how impossible values like -50 health sneak into games.

  2. 2

    Methods are the only door

    takeDamage(amount) changes health and enforces the rule: if (this.health < 0) this.health = 0; No matter who calls it or how hard the hit, the rule always runs.

  3. 3

    Try it

    Call takeDamage(99) and check the health — it stops at 0, never goes negative. Add a heal() method with its own rule: never above 10.

Code Editor

Protect object data with methods.

Example code
class Player {
  constructor(name) {
    this.name = name;
    this.health = 10;
  }

  takeDamage(amount) {
    this.health -= amount;
    if (this.health < 0) {
      this.health = 0;
    }
  }

  heal(amount) {
    this.health += amount;
    if (this.health > 10) {
      this.health = 10;
    }
  }

  status() {
    say(this.name + " has " + this.health + " health.");
  }
}

let hero = new Player("Nova");
hero.takeDamage(3);
hero.heal(1);
hero.status();
Output

Program result

Robot ready to speak your strings

Type real JavaScript, then run it.