Back to Encapsulation Builder
OOP Studio Ages 9-15

Encapsulation Challenge

Create a class that protects a value and uses methods to change it only when the change makes sense.

10-15 min Ages 9-15 OOP Challenge JavaScript
Code Editor

Create a safe object system.

Example code
class BankAccount {
  constructor(owner) {
    this.owner = owner;
    this.balance = 0;
  }

  deposit(amount) {
    if (amount > 0) {
      this.balance += amount;
      say(this.owner + " deposited " + amount + " coins.");
    }
  }

  spend(amount) {
    if (amount <= this.balance) {
      this.balance -= amount;
      say(this.owner + " spent " + amount + " coins.");
    } else {
      say("Not enough coins.");
    }
  }

  report() {
    say(this.owner + " has " + this.balance + " coins.");
  }
}

let account = new BankAccount("Kai");
account.deposit(8);
account.spend(3);
account.spend(10);
account.report();
Output

Program result

Robot ready to speak your strings

Type real JavaScript, then run it.