Introduction

  • Encapsulation is the mechanism of binding the data together and hiding it from the outside world.
  • Encapsulation is achieved when each object keeps its state private so that other objects don’t have direct access to its state. Instead, they can access this state only through a set of public functions.
public class BankAccount {
    // Private variables: internal state is hidden
    private double balance;
 
    // Public method to interact with the balance
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
 
    // Public method to interact with the balance
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
        }
    }
 
    // Public method to get the balance
    public double getBalance() {
        return balance;
    }
}

In this example, the balance is a private variable, meaning it can’t be accessed or modified directly from outside the BankAccount class. Instead, you interact with it through the deposit, withdraw, and getBalance methods. This ensures that the balance can only be changed in specific, controlled ways, protecting the integrity of the data.

To Give You An Analogy, Encapsulation Works Like A Capsule Where The Medicine Inside The Pill Would Be Data And Methods While The Outer Covering Would Be The Hard Shell Capsule. 

Key Points of Encapsulation:

  1. Bundling Data and Methods:
    • Class: A blueprint for creating objects, containing attributes (data) and methods (functions).
    • Object: An instance of a class that can have its own unique values for the attributes defined by the class.
  2. Hiding Implementation Details:
    • Encapsulation hides the complex inner workings of a class, exposing only what is necessary through a public interface.
    • This makes the code easier to use and reduces the chance of errors.
  3. Access Modifiers: Access modifiers define the scope of a class, constructor, method, or field.
    • Public: Accessible from anywhere in the program.
    • Private: Accessible only within the class it is defined. Can only be accessed via the public method in class by the outside world, after instantiating the object of that class.
    • Protected: Accessible within the class and its subclasses.
    • Default (no modifier): The member is accessible only within its own package.

Why Use Encapsulation?

  • Security: By restricting access to certain parts of the code, encapsulation helps protect data from being accidentally modified.
  • Simplicity: Users of a class do not need to understand its inner workings. They just need to know how to interact with it.
  • Flexibility: The implementation details of a class can be changed without affecting the code that uses the class.