Junior — Middle
Can you give an example of encapsulation in object-oriented programming?
sobes.tech AI
Answer from AI
Encapsulation is an OOP principle that allows hiding the internal implementation details of an object and providing access to data and methods through a public interface.
Example in JavaScript (Node.js):
class BankAccount {
#balance; // private field
constructor(initialBalance) {
this.#balance = initialBalance;
}
deposit(amount) {
if (amount > 0) {
this.#balance += amount;
}
}
withdraw(amount) {
if (amount > 0 && amount <= this.#balance) {
this.#balance -= amount;
return amount;
}
return 0;
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount(1000);
account.deposit(500);
console.log(account.getBalance()); // 1500
// Cannot directly change the balance:
// account.#balance = 100000; // Error
Here, the #balance field is hidden from external access, which protects the data from incorrect modification.