What is Encapsulation?
Encapsulation and information hiding, told as a story about a writer who hides draft notes in a drawer and only hands finished chapters through a submission box.
The editor reaches straight into the writer's drawer and edits the notes.The inside of the drawer was supposed to be the writer's alone.
With everyone reaching into each other's drawers, the notes stop lining up.When anyone can touch what's in a drawer, the notes stop matching up.
Encapsulation hides the drawer's inside and hands things over only through a fixed box.Change what's in the drawer, and if the box's shape stays the same, nobody outside notices.
Unfinished notes stay in the locked drawer; only finished chapters go in the submission box.Change what's in the drawer, and nobody outside notices as long as the box's shape stays the same.
Encapsulation doesn't catch a mistake in the design itself.Encapsulation hides the inside — it doesn't guarantee the design itself is right.
Encapsulation and information hiding bundle data and behavior together, hide the inside, and expose only a fixed interface to the outside.
Encapsulation bundles an object's data and methods together and exposes only a public interface, hiding the internal implementation (information hiding) — a core OOP principle. Because the private internals can change freely as long as the external interface stays the same, it makes code resilient to change and prevents unintended direct manipulation.
When grown-ups say it
- Encapsulation
- Bundling data and behavior together. Hides the inside, exposes only the box.
- Information Hiding
- Locking the drawer. The design principle of hiding internals from the outside; encapsulation is the main way to achieve it.
- Public Interface
- The submission box. The only way in or out from the outside.
- Private Field
- Notes inside the locked drawer. The outside can't touch it directly.
- Getter/Setter
- The clerk's hand that fetches a note for you. Instead of opening the drawer, it hands notes over only the agreed way.
- Modularity
- Giving every desk its own drawer. The better a part hides its inside, the easier it is to split off as its own module.
- Refactoring
- Tidying up the notes inside the drawer. The box stays the same while the inside gets tidied. → keep the outside, retouch the inside
- Unit Test
- Checking by feeding things straight into the box. You can verify the behavior by watching just the public box.