Encapsulation

Data hiding and bundling

Overview

Encapsulation is the bundling of data (attributes) and methods that operate on that data within a single unit (class), while hiding the internal details from the outside world. It's achieved using access modifiers.

Key Concepts

Data hiding: Private attributes not accessible from outside

Access modifiers: public, private, protected, default

Getters and Setters: Controlled access to private data

Information hiding: Internal implementation hidden from users

Modularity: Changes in one class don't affect others

Code Example

java
1public class BankAccount {
2    // Private attributes - hidden from outside
3    private String accountNumber;
4    private double balance;
5    private String ownerName;
6    
7    public BankAccount(String accountNumber, String ownerName) {
8        this.accountNumber = accountNumber;
9        this.ownerName = ownerName;
10        this.balance = 0.0;
11    }
12    
13    // Public methods - controlled access
14    public void deposit(double amount) {
15        if (amount > 0) {
16            balance += amount;
17            System.out.println("Deposited: $" + amount);
18        } else {
19            System.out.println("Invalid deposit amount");
20        }
21    }
22    
23    public boolean withdraw(double amount) {
24        if (amount > 0 && amount <= balance) {
25            balance -= amount;
26            System.out.println("Withdrawn: $" + amount);
27            return true;
28        }
29        System.out.println("Insufficient funds or invalid amount");
30        return false;
31    }
32    
33    // Getter - read-only access
34    public double getBalance() {
35        return balance;
36    }
37    
38    // No setter for balance - can only change through deposit/withdraw
39    
40    public String getAccountNumber() {
41        return accountNumber;
42    }
43}
44
45// Usage
46public class Main {
47    public static void main(String[] args) {
48        BankAccount account = new BankAccount("1234567890", "John Doe");
49        
50        // Cannot directly access: account.balance = 1000000; // Compilation error!
51        
52        // Must use public methods
53        account.deposit(1000);
54        account.withdraw(500);
55        System.out.println("Balance: $" + account.getBalance());
56    }
57}

The balance is private and can only be modified through deposit() and withdraw() methods, ensuring data integrity.

Advantages

  • Data security - prevents unauthorized access

  • Flexibility - can change internal implementation without affecting users

  • Maintainability - easier to update and debug

  • Modularity - classes are self-contained units

  • Reusability - well-encapsulated classes can be reused

Real-World Example

Consider a car: You interact with it through the steering wheel, pedals, and gear shift (public interface), but you don't need to know how the engine works internally (private implementation). The manufacturer can improve the engine without changing how you drive.

Similarly, a TV remote is the public interface, while the internal circuitry is encapsulated.

Best Practices

  • 1.

    Make all attributes private by default

  • 2.

    Provide public getters/setters only when necessary

  • 3.

    Validate data in setters before updating attributes

  • 4.

    Use immutable classes where appropriate (no setters)

  • 5.

    Hide complex logic behind simple public methods

💡 Interview Tips

  • Explain encapsulation as "data hiding" + "bundling"

  • Give the BankAccount example to show controlled access

  • Discuss how it helps in maintaining code

  • Mention it's one of the four pillars of OOP

  • Be ready to write a practical example during coding

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In
Encapsulation - OOP Fundamentals | LLD | Revise Algo