1. Definition
  2. Need
  3. How to achieve
  4. Real-World Example
  5. Packages (In Java)

1. Definition

Encapsulation is one of the core principles of object-oriented programming (OOP). It involves bundling the data (attributes) and the methods (functions) that operate on the data into a single unit, typically called a class.

The key aspects of encapsulation include:

  1. Data Hiding: Encapsulation allows a class to hide its internal data from outside access and modification. This is achieved by making the data members (variables) private or protected, while providing public methods (getters and setters) to access and modify the data in a controlled manner. This ensures that the internal state of an object can only be changed in well-defined ways.
  2. Abstraction: By encapsulating the implementation details of a class, the complexity is hidden from the user. The user interacts with the object through its public methods, without needing to know the internal workings. This abstraction makes it easier to use and maintain the code.
  3. Control and Security: Encapsulation provides control over the data. By restricting direct access to data members, you can enforce rules and validation, ensuring that the data remains in a valid state.

Example

Consider a simple class representing a bank account:

class BankAccount {
    private var balance: Double = 0.0  // Private data member

    // Public method to deposit money
    public func deposit(amount: Double) {
        if amount > 0 {
            balance += amount
        }
    }

    // Public method to withdraw money
    public func withdraw(amount: Double) -> Bool {
        if amount > 0 && amount <= balance {
            balance -= amount
            return true
        } else {
            return false
        }
    }

    // Public method to get the current balance
    public func getBalance() -> Double {
        return balance
    }
}

2. Need

1. Data Protection