Unit 3 · OOP Concepts

3.4Encapsulation

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.

BankAccountprivateaccountNobalancegetBalance()setBalance(x)withdraw(x)other codeallowedacc.balance = -500 ✗setter checks:if (balance >= 0)else reject
Encapsulation: private data can only be reached through public methods, which check every change

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 private so 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.

In this section