Encapsulation

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Encapsulation is the mechanism of hiding the internal state (data) of an object and requiring all interaction to be performed through an object’s methods.
  • It is achieved by making class fields private and providing public getter and setter methods.
  • Also known as Data Hiding.

Concept

Encapsulation ensures that an object maintains control over its own state. If fields are public, any outside class can change them to invalid values. By making them private, the class acts as a gatekeeper.

Benefits:

  1. Validation: Setters can contain logic to validate data before assigning it.
  2. Read-Only / Write-Only: You can omit a setter to make a field read-only, or omit a getter to make it write-only.
  3. Flexibility: You can change the internal implementation of a class without breaking the code of external classes that use it (because they only rely on the public methods).

Examples

class BankAccount {
    // 1. Hide the data
    private double balance;
    
    public BankAccount(double initialBalance) {
        this.balance = initialBalance;
    }
    
    // 2. Provide public getter (Read access)
    public double getBalance() {
        return balance;
    }
    
    // 3. Provide public setter with VALIDATION (Controlled write access)
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        } else {
            System.out.println("Cannot deposit negative amounts.");
        }
    }
}

Interview Questions

Q: How is Encapsulation different from Abstraction?
A: - Encapsulation is about hiding the internal state and protecting data integrity. It’s an implementation-level concept achieved via access modifiers (private).

  • Abstraction is about hiding the complex implementation details and showing only the essential features of an object. It’s a design-level concept achieved via Interfaces and Abstract classes.
    (Mnemonic: Encapsulation hides the data, Abstraction hides the how.)

Q: What are the consequences of not using encapsulation?
A: If you make class fields public, you lose control over them. A user could set an age field to -500, or a balance field to NaN, leading to corrupted state and unpredictable application bugs. It also tightly couples external code to your internal data structure, making future refactoring very difficult.