Objects and behaviour
What is encapsulation?
On this page
Encapsulation gives an object a boundary around its representation and operations. A Range can reject an upper bound smaller than its lower bound during construction. Returning a mutable internal list from a getter can break that boundary even if the field itself is private.
Worked example
JavaScriptclass Window {
#lower;
#upper;
constructor(lower, upper) {
if (upper < lower) throw new RangeError("Reversed window");
this.#lower = lower;
this.#upper = upper;
}
contains(x) { return this.#lower <= x && x < this.#upper; }
}
const windowRange = new Window(9, 12);
if (!windowRange.contains(9) || windowRange.contains(12)) {
throw new Error("Expected a half-open interval");
}Explore class relationships in the OOP Playground