Definition. Encapsulation
[comp1110-3F]
Definition. Encapsulation
[comp1110-3F]By marking fields as private, we hide the internal state. We then provide public methods (the interface) as the only way to interact with that state. This is important for two reasons:
- Integrity - we can maintain data invariants about the object's internal state: properties that should be true before and after each call to a method on the object. For example, in Example [comp1110-3E],because balance is private, a user cannot write
account.balance = -500;. They are forced to use deposit(), where we can include logic to ensure that the balance never goes negative. This enforces the data invariant that the account balance is always \(\geq 0\). - Abstraction - we can separate the interface (what methods are exposed to the
public) from the implementation (the private fields and method implementations). This means that users of this class need only know about the interface, which reduces cognitive load on the programmer — essential for large programs. It also enables flexibility. For example, in Example [comp1110-3E], if we later decide to store the balance in a different currency or a different data type, we only change the code inside the class. Anyone callinggetBalance()won't even notice the change.