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.
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();
Program result
- Run your code to see output.
Type real JavaScript, then run it.
Encapsulation challenge complete.
You made an object that protects its value and changes it through careful methods.
Finish Encapsulation Challenge