Encapsulation and Abstraction
Keep data private so a class can protect its own rules, and expose a small "what" while hiding the "how".
The problem it solves
If every field is public, any code anywhere can put an object into a state it was never meant to have: a negative balance, a playlist over its limit, a date of 31 February.
- Encapsulation: bundle data with the methods that use it, and make the data private. The only way in is through methods that check the rules.
- Invariant: a rule that must always hold for an object, such as "balance is never negative". The class is responsible for keeping its own invariants true.
- Abstraction: show callers a small, stable set of operations (the "what") and hide how they work (the "how").
The two are related but different. Encapsulation is about protecting state. Abstraction is about simplifying the view.
1 of 6