Intern — Junior
What is the role of encapsulation in object-oriented programming?
sobes.tech AI
Answer from AI
Encapsulation in object-oriented programming is a principle that allows hiding the internal implementation details of an object and providing access to data and methods only through a defined interface.
The role of encapsulation:
- Data protection: prevents direct access to internal fields of an object, helping to avoid unintended modifications.
- Simplifies usage: users interact with the object through public methods without worrying about internal implementation.
- Increases flexibility: internal implementation can be changed without affecting code that uses the object.
Example in JavaScript (Node.js):
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.checkPassword('secret')); // true
// user.#password - error, access denied
Thus, encapsulation helps create more reliable and maintainable code.