Encapsulation in Java

Encapsulation in Java is a mechanism that combines data and methods into a single unit called a class. It involves hiding the internal details and implementation of an object and exposing only the necessary information through methods. The encapsulated data is typically accessed and modified through methods, which are known as accessors (getters) and mutators (setters).

Advantages of Encapsulation

  1. Data Hiding: Encapsulation allows you to hide the internal state and implementation details of an object. The data members of a class are declared as private, preventing direct access from outside the class. This protects the integrity and consistency of the object's data and prevents unauthorized modifications.

  2. Data Protection: By providing controlled access to the data, encapsulation helps in enforcing business rules and constraints. The class can define validation logic and perform necessary checks before allowing modifications to the data, ensuring data integrity.

  3. Code Flexibility and Maintainability: Encapsulation promotes modular and organized code. By encapsulating related data and methods within a class, it becomes easier to understand and maintain the code. Changes to the internal implementation of the class do not affect other parts of the program as long as the public interface remains the same.

  4. Code Reusability: Encapsulation enables code reusability. Once a class is encapsulated, it can be used in other parts of the program without exposing its internal implementation. This promotes code reuse and saves development time.

Example of Encapsulation:

public class BankAccount {
    private String accountNumber;
    private double balance;
    
    public String getAccountNumber() {
        return accountNumber;
    }
    
    public void setAccountNumber(String accountNumber) {
        this.accountNumber = accountNumber;
    }
    
    public double getBalance() {
        return balance;
    }
    
    public void deposit(double amount) {
        balance += amount;
    }
    
    public void withdraw(double amount) {
        if (amount <= balance) {
            balance -= amount;
        } else {
            System.out.println("Insufficient funds");
        }
    }
}

In this example, the BankAccount class encapsulates the account number and balance as private data members. The accessors (getAccountNumber() and getBalance()) provide read-only access to the data, while the mutators (setAccountNumber(), deposit(), and withdraw()) allow controlled modifications to the data.

Encapsulation ensures that the account number and balance can only be accessed and modified through the defined methods. The class hides the implementation details and protects the data from direct unauthorized access, maintaining data integrity and enforcing business rules.