Encapsulation
MediumIn plain terms
Encapsulation is the idea of keeping data and the code that uses it together, and hiding internal implementation details. The outside world interacts through a clear interface (public methods); they do not need to know how data is stored or how a result is computed.
Benefits: you can change internals without breaking callers, and you prevent invalid state (e.g. only allow changing balance through deposit/withdraw, not by setting a number directly). In many languages, "private" fields and "public" methods enforce encapsulation.
What you need to know
- •Bundle data and behavior
- •Hide implementation details
- •Public interface vs private state
Example
Code is language-agnostic in spirit; adapt the idea to your language:
class BankAccount {
#balance = 0; // private
deposit(amount) {
if (amount > 0) this.#balance += amount;
}
withdraw(amount) {
if (amount > 0 && amount <= this.#balance)
this.#balance -= amount;
}
getBalance() {
return this.#balance; // controlled access
}
}Why this matters
Encapsulation is one of the four OOP pillars and is frequently asked. Interviewers want to hear "data hiding," "controlled access," and "change internals without breaking callers."
How it connects
Encapsulation supports Single Responsibility (one place owns the data) and Open/Closed (extend via new classes without changing internal state of existing ones). Private fields and getters/setters are the main tools.
Interview focus
Be ready to explain these; they come up often.
- ▸Definition: bundle data and methods; hide internals; expose a clear interface.
- ▸Benefits: maintainability, preventing invalid state, flexibility to change implementation.
- ▸How: access modifiers (private/protected/public), getters/setters where needed.
Learn more
Dive deeper with these resources: