Explain encapsulation with an example.
Show answer and explanation
Encapsulation packages state with the operations that maintain its invariants and hides representation details behind a stable interface. It is not merely making fields private and adding unrestricted getters and setters: callers should express valid domain operations, such as withdraw, while the class rejects invalid transitions such as a negative balance. This reduces coupling and lets the implementation change without forcing callers to change.
Encapsulation packages state with the operations that maintain its invariants and hides representation details behind a stable interface. It is not merely making fields private and adding unrestricted getters and setters: callers should express valid domain operations, such as withdraw, while the class rejects invalid transitions such as a negative balance. This reduces coupling and lets the implementation change without forcing callers to change.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.