Encapsulation
Encapsulation keeps an object's state and the code that guards it in one place, and lets nothing else change that state directly. It is how a class keeps its promises.
Overview
Encapsulation puts data and the operations on that data in one class, and closes every other door to the data. A BankAccount keeps its balance private; the only ways to change it are deposit and withdraw, and those methods enforce the rules: no negative amounts, no overdraft beyond the limit, every change recorded. Because no other code can touch the balance, those rules hold everywhere, forever.
The practical value is in the numbers. An invariant (a rule about state that must always be true) is only as strong as the number of places that can break it. With a public field, that number is 'every file in the codebase'. With a private field and two methods, it is two. Encapsulation also buys freedom: the class can change how it stores the balance, from an integer to a ledger of entries, and no caller notices.
The state and its rules, in one place
The class diagram shows the whole idea in one picture. Every field of BankAccount is private, marked with a minus sign, and every public method, marked with a plus sign, is a door with a rule behind it.
That one door buys four things. Invariants hold, because the only code that writes the field also checks the rule. The class is free to change its representation, because callers see methods, not fields. There is a smaller surface to learn and test, because the public methods are the whole story. And concurrency is safe to add later, because a lock inside the class covers every path to the state.
Interview questions
- What are the access modifiers, and when do you use each?
- Are getters and setters better than public fields?
- How do you stop a getter from leaking a mutable reference?
- What is tell-don't-ask, and how does the Law of Demeter follow from encapsulation?
- How does immutability relate to encapsulation?
- How do Java, Python and JavaScript enforce encapsulation differently?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio