BhauAutomation

Java Encapsulation

Encapsulation in Java is one of the four fundamental Object-Oriented Programming (OOP) principles. It is the process of wrapping data (variables) and code (methods) together as a single unit to protect data and maintain control over it. Encapsulation is also known as Data Hiding.

📘 Topic: Core Java / OOPs
Read time: 6 min
📊 Level: Intermediate
🔒 Focus: Data Hiding & Security
📖 Overview

What is Encapsulation?

Encapsulation means restricting direct access to some of an object's components. This is achieved using access modifiers like private, protected, and public. Encapsulation ensures that data is hidden and controlled properly through getter and setter methods. It bundles data and methods that operate on that data within a single unit (the class).

For example, a BankAccount class keeps the balance variable private and provides public methods like deposit() and withdraw() to modify it safely with validation logic.

🎯 Objectives

Objectives of Encapsulation

🔒 Protect Object Data: The main objectives of encapsulation are to protect object data from unauthorized access, improve code maintainability, and control how important variables are accessed or modified.

🔧 Improve Maintainability: By hiding internal implementation details, you can change the internal logic without affecting external code that uses the class.

✅ Ensure Data Integrity: By using encapsulation, you can add validation logic in setter methods to ensure that objects always remain in a valid state.

✅ Advantages

Advantages of Encapsulation

🛡️ Data Hiding & Security: Encapsulation hides sensitive data from outside access, ensuring the security of object data.

🔧 Flexibility & Reusability: Internal implementation can change without affecting outside code, making the code flexible and reusable.

🐞 Easier Debugging & Maintenance: Since access to variables is controlled through getters and setters, bugs are easier to trace and fix.

🎯 Controlled Access: You can add validation logic in setter methods to ensure that only valid values are assigned to variables.

⚠️ Limitations

Limitations of Encapsulation

📝 Increased Code Size: Using encapsulation can increase code size because of the additional getter and setter methods.

🐌 Complexity Overhead: If not designed properly, encapsulation can make debugging more complex and add unnecessary abstraction.

⚠️ Not Automatic: Encapsulation is not effective unless proper access control (private variables + public getters/setters) is implemented for all sensitive variables.

⚙️ How It Works

How Encapsulation Works in Java

In Java, encapsulation works by declaring class variables as private and providing public setter and getter methods. These methods allow controlled access to the variables instead of accessing them directly.

1

Declare class variables as private

2

Create public getter methods to read values

3

Create public setter methods to update values with validation

📝 Getter & Setter

Getter and Setter Methods

📖 Getter Method

Used to retrieve (get) the value of a private variable. Typically named as getVariableName().

✏️ Setter Method

Used to modify (set) the value of a private variable. Typically named as setVariableName() and can include validation logic.

💻 Code Example

Encapsulation Example

BankAccount Class with Encapsulation:

class BankAccount {
    private String accountNumber;
    private double balance;
    private String accountHolderName;

    // Constructor
    public BankAccount(String accountNumber, String accountHolderName, double initialBalance) {
        this.accountNumber = accountNumber;
        this.accountHolderName = accountHolderName;
        if (initialBalance >= 0) {
            this.balance = initialBalance;
        }
    }

    // Getter methods
    public String getAccountNumber() {
        return accountNumber;
    }

    public double getBalance() {
        return balance;
    }

    public String getAccountHolderName() {
        return accountHolderName;
    }

    // Setter with validation
    public void setAccountHolderName(String name) {
        if (name != null && !name.trim().isEmpty()) {
            this.accountHolderName = name;
        }
    }

    // Business methods
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("Deposited: " + amount);
        }
    }

    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("Withdrawn: " + amount);
        } else {
            System.out.println("Insufficient balance!");
        }
    }
}

public class EncapsulationDemo {
    public static void main(String[] args) {
        BankAccount account = new BankAccount("ACC123", "Bhau Automation", 10000.0);
        
        // Using getters to access data
        System.out.println("Account Holder: " + account.getAccountHolderName());
        System.out.println("Account Number: " + account.getAccountNumber());
        System.out.println("Current Balance: " + account.getBalance());
        
        // Using business methods to modify data
        account.deposit(5000);
        account.withdraw(3000);
        System.out.println("Final Balance: " + account.getBalance());
        
        // Using setter to update name
        account.setAccountHolderName("Bhau Automation Academy");
        System.out.println("Updated Holder: " + account.getAccountHolderName());
    }
}
🏆 Best Practices

Best Practices for Encapsulation

Always keep class variables private by default (defensive programming)

Use public getter and setter methods for controlled access

Add validation logic in setter methods to maintain data integrity

Encapsulate related data and behavior within one class

For immutable objects, provide only getters (no setters)

Use meaningful names for getter and setter methods following JavaBeans convention