Sobes.tech
Junior — Middle

Can you explain the concept of encapsulation in object-oriented programming?

sobes.tech AI

Answer from AI

Encapsulation is a principle of object-oriented programming that involves combining data (properties) and methods that work with this data within a single object or class. It allows hiding the internal state of an object and providing access to it only through certain methods (getters and setters), which protects the data from being modified directly from outside.

For example, in JavaScript, you can create a private property using a symbol or follow a convention with an underscore:

class User {
  #password; // private field

  constructor(name, password) {
    this.name = name;
    this.#password = password;
  }

  checkPassword(input) {
    return input === this.#password;
  }
}

const user = new User('Alice', '12345');
console.log(user.name); // Alice
console.log(user.#password); // Error, access denied
console.log(user.checkPassword('12345')); // true

Thus, encapsulation helps control access to data, enhances security, and simplifies code maintenance.