Browse OOP reference
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

JavaScript
class 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");
}

MDN on JavaScript private elements

Explore class relationships in the OOP Playground

What is an object?What is object-oriented programming?How does object-oriented design apply to AI engineering?

All OOP questions

Search ObjectFAQ