Encapsulation is bundling attributes and methods in one class and hiding the internal data, so that it can only be accessed or changed through controlled public methods.
Real-life analogy: a medicine capsule hides its contents. A car's accelerator pedal lets you change speed without touching the engine.
Why encapsulation matters
Imagine that a BankAccount had a public balance. Any line of code, in any class, could write acc.balance = -1000000;, and nothing would stop it. If a balance is ever wrong, you would have to search the whole program to find out which line did it.
With encapsulation the balance is private, and the only way to change it is through deposit() and withdraw(). Those two methods check every change, so an invalid balance can never happen. If a bug does appear, you know it must be inside the class. The class becomes responsible for keeping its own data correct.
Key words in this topic
- Data hiding: making attributes
privateso that no other class can use them directly. - Getter (accessor): a public method that returns the value of an attribute.
- Setter (mutator): a public method that changes an attribute, after checking that the new value is valid.
- Validation: checking a value before accepting it.
- Read-only attribute: an attribute that has a getter but no setter.