Encapsulation contains a class's data and behavior, hides implementation details, and gives client code a controlled public interface. Its practical purpose is preserving the class invariant: every instance remains meaningful and predictable. section 7.2.1 section 9.12
A common mistake is writing accessors and mutators for every private variable. Trivial accessors expose representation, encourage clients to manage internal state, dilute essential methods, and make later changes harder. Expose behavior clients need rather than storage they can inspect. section 8.2
Apply encapsulation by:
- Keeping state and the knowledge needed to validate it inside the class. section 7.2.1
- Avoiding stored values that merely duplicate derived state; compute results through behavior when appropriate. section 8.2
- Minimizing member functions that directly depend on representation, so a new representation changes fewer methods. section 9.12
Circle: expose computation, not cached representation
A Circle that stores both radius and area makes area an exposed implementation detail through getArea(). A safer form stores radius and computes radius*radius*PI in the accessor, avoiding duplicated state that can become inconsistent.













