Encapsulation
In short: The principle of protecting the internal data of an object from direct access from outside, and instead making it accessible only via defined methods (getters/setters).
In more detail: Instead of making a field directly public, it’s kept private (see access modifiers) and access is regulated via controlled methods — this way, for example, an age field can be prevented from being set to a negative value, because the setter can check this beforehand. Encapsulation is one of the four core principles of OOP and makes code more robust against faulty use from outside.
In Depth
The core idea: an object should be responsible for its own internal state and be able to guarantee that this state always stays valid — that only works if outsiders can’t simply change this state directly, bypassing the control logic.
class Account {
private balance: Number
deposit(amount) {
if amount <= 0:
error("Amount must be positive")
balance = balance + amount
}
withdraw(amount) {
if amount > balance:
error("Not enough balance")
balance = balance - amount
}
}If balance were instead a public field, any caller could set it directly to any (even invalid, e.g. negative) value, with the Account class unable to prevent or even notice it. With encapsulation, deposit()/withdraw() is the ONLY way to change the balance — the class has full control over its own invariants (rules that must always hold).
An often overlooked additional benefit: encapsulation allows the internal implementation to be changed later, without adjusting code that uses the class from outside — as long as the public interface (the method signatures) stays the same. balance could, for example, later be stored internally in cents instead of euros, with callers of deposit()/withdraw() not noticing anything about it at all.
A common beginner mistake that effectively defeats encapsulation: formally keeping a private field private, but returning a getter that directly hands out a MUTABLE reference to an internal object (e.g. a list) — the caller can then still modify this list from outside, even though it was technically never directly assigned. It’s cleaner to either return a copy or an immutable view of the data.