Back to Academy
oop
Encapsulation
Encapsulation bundles data with the methods that operate on it and restricts direct access to internal state. Like an ATM that lets you withdraw money without exposing the vault's combination, encapsulation protects invariants by forcing all mutations through controlled methods that can validate input and maintain consistency.
Use Cases
- •Protecting account balances from being set to negative values via direct assignment
- •Hiding database connection details behind a repository interface
- •Enforcing valid state transitions in order processing (pending → paid → shipped)
- •Wrapping third-party API credentials so they cannot be accidentally logged
Implementation
Output
Click "Run Code" to see output...