Β 

πŸ”’ Encapsulation in Java – Data Security Made Simple

When we talk about OOP in Java, one of the most powerful principles is Encapsulation. Think of it as putting sensitive data inside a box and only opening it with a proper key (methods).


🌟 What is Encapsulation?

πŸ‘‰ Encapsulation is the process of hiding data (variables) inside a class and providing controlled access using methods (getters & setters).
It prevents direct access to data and protects it from unwanted modification.


🏦 Real-World Analogy

  • Imagine your ATM card & PIN.

    • Your bank balance (data) is hidden.

    • You can’t directly take money out from the vault.

    • You use an ATM machine (methods) to access your balance safely.

That’s Encapsulation in action!


⚑ Key Points of Encapsulation

  • βœ… Class variables are kept private.

  • βœ… Public methods (getters & setters) are used to access or modify data.

  • βœ… Provides data security.

  • βœ… Increases code maintainability & flexibility.


πŸ–₯️ Java Example: Encapsulation in Action

class BankAccount {
    // Private data
    private String accountHolder;
    private double balance;

    // Getter method
    public String getAccountHolder() {
        return accountHolder;
    }

    // Setter method
    public void setAccountHolder(String name) {
        this.accountHolder = name;
    }

    // Getter method
    public double getBalance() {
        return balance;
    }

    // Setter method
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount acc = new BankAccount();
        acc.setAccountHolder("Ravi");
        acc.deposit(5000);

        System.out.println("Account Holder: " + acc.getAccountHolder());
        System.out.println("Balance: " + acc.getBalance());
    }
}

βœ… Output:

Account Holder: Ravi  
Balance: 5000.0  

🎯 Benefits of Encapsulation

  • πŸ” Security β†’ Data is safe from unauthorized access.

  • πŸ›  Flexibility β†’ Easy to change the code later without breaking other parts.

  • πŸ“¦ Reusability β†’ Encapsulated classes can be reused across projects.

  • πŸš€ Maintainability β†’ Changes in one part don’t affect the whole program.


✨ Quick Summary

πŸ‘‰ Encapsulation = Data + Methods bundled together in a class with restricted access.
It ensures security, control, and clean code architecture.

πŸ’‘ Pro Tip: Always make your variables private and provide public getter/setter methods when needed.

Β