AlgoMaster Logo

Encapsulation

Ashish

Ashish Pratap Singh

Encapsulation is one of the four foundational principles of object-oriented design. It is the practice of grouping data (variables) and behavior (methods) that operate on that data into a single unit (typically a class) and restricting direct access to the internal details of that class.

In simple terms:

Encapsulation = Data hiding + Controlled access

In programming, Encapsulation is typically achieved using:

  • Access Modifiers (privateprotectedpublic)
  • Getter and Setters

Why Encapsulation Matters

It helps you build systems that are robust, secure, and easy to maintain. Here's why it's essential:

  • Data Hiding: By restricting direct access to internal fields, encapsulation shields sensitive data from unintended interference or misuse.
  • Controlled Access and Security: : It ensures that data can only be accessed or modified through well-defined methods, allowing you to enforce rules, validation, or logging when needed.
  • Improved Maintainability: Because internal implementation details are hidden, you can refactor or optimize them without affecting the external code that depends on the class.

In a well-encapsulated design, external code doesn’t need to know how something is done, it only needs to know what can be done.

Code Example

Let’s look at two practical examples that demonstrate how encapsulation helps you protect internal state, enforce business rules, and expose only what’s necessary.

Example 1: BankAccount

In a banking system, you want users to deposit and withdraw funds, but you must prevent direct manipulation of the account balance. Here’s how encapsulation helps:

  • balance is marked private, so no external class can access or modify it directly.
  • deposit() and withdraw() are public entry points that validate user input before updating the state.
  • getBalance() allows read-only access, without revealing the underlying variable or letting external code change it.

This ensures the account remains in a valid state at all times and business rules are enforced through controlled interfaces.

Example 2: PaymentProcessor

In this example, a PaymentProcessor class accepts a card number and amount, but internally masks the card number to protect user privacy. Again, encapsulation allows us to hide implementation details while offering a clean interface.

Output:

  • The raw card number is never stored or exposed directly.
  • Masking is handled internally via a private method.
  • The external caller doesn’t need to know how masking is done, they just call processPayment().

This design secures sensitive data and centralizes masking logic in one place, making the system safer and easier to maintain.