Sobes.tech
Junior — Middle

Can you explain the concept of data hiding inside objects in object-oriented programming?

sobes.tech AI

Answer from AI

Data hiding (encapsulation) in object-oriented programming means restricting access to the internal states of an object and providing access to them only through the object's methods (functions).

This helps protect data from incorrect usage and modifications from outside, maintaining the integrity of the object.

For example, in JavaScript (Node.js), private fields and methods can be used:

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', 'secret');
console.log(user.name); // Alice
console.log(user.#password); // Error: private field
console.log(user.checkPassword('secret')); // true

Thus, internal data (e.g., password) is hidden from direct access, and interaction with it occurs through controlled methods.