Java Encapsulation

Encapsulation is the process of bundling data (fields) and methods that operate on that data into a single unit (class), and restricting direct access to the internal state of an object. It is one of the four pillars of OOP and is the foundation of data protection in Java.

Encapsulation is achieved by:

  1. Declaring class fields as private.
  2. Providing public getter and setter methods to read and modify the fields in a controlled way.

Real-World Analogy

Think of an ATM machine. The internal cash mechanism, software, and communication systems are all hidden from the user. The user interacts only through a controlled interface (card slot, keypad, screen). The internal workings are encapsulated — protected and inaccessible directly.

Access Modifiers

Understanding access modifiers is key to encapsulation. They control who can access a field or method.

ModifierSame ClassSame PackageSubclassOther Packages
privateYesNoNoNo
default (none)YesYesNoNo
protectedYesYesYesNo
publicYesYesYesYes

Implementing Encapsulation

Step 1 – Make Fields Private

class BankAccount {
    private String accountNumber;
    private double balance;
    private String owner;
}

Fields declared as private cannot be accessed from outside the class.

Step 2 – Provide Public Getters and Setters

Getter methods read the value of a private field. Setter methods update it, with optional validation.

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

    // Getter methods
    public String getAccountNumber() { return accountNumber; }
    public double getBalance() { return balance; }
    public String getOwner() { return owner; }

    // Setter methods with validation
    public void setBalance(double balance) {
        if (balance < 0) {
            System.out.println("Balance cannot be negative.");
        } else {
            this.balance = balance;
        }
    }

    public void setOwner(String owner) {
        if (owner == null || owner.isEmpty()) {
            System.out.println("Owner name cannot be empty.");
        } else {
            this.owner = owner;
        }
    }

    public void setAccountNumber(String accountNumber) {
        this.accountNumber = accountNumber;
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount();
        account.setAccountNumber("ACC-001");
        account.setOwner("Alice");
        account.setBalance(5000.00);

        System.out.println("Account: " + account.getAccountNumber());
        System.out.println("Owner: " + account.getOwner());
        System.out.println("Balance: " + account.getBalance());

        account.setBalance(-100);   // validation kicks in
    }
}

Output:

Account: ACC-001
Owner: Alice
Balance: 5000.0
Balance cannot be negative.

Read-Only and Write-Only Fields

Read-Only (Only a Getter)

If only a getter is provided and no setter, the field becomes read-only from outside the class. This is useful for immutable values.

class Student {
    private final int studentId;

    Student(int studentId) {
        this.studentId = studentId;
    }

    public int getStudentId() {
        return studentId;   // read-only
    }
    // No setter – studentId cannot be changed once set
}

Write-Only (Only a Setter)

Rarely used, but a write-only field has only a setter. It can receive values but cannot be read externally — useful for passwords.

class SecureLogin {
    private String password;

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean checkPassword(String input) {
        return this.password.equals(input);
    }
    // No getter – password cannot be read from outside
}

Encapsulation in Practice – Complete Example

class Employee {
    private String name;
    private int age;
    private double salary;

    public Employee(String name, int age, double salary) {
        this.name = name;
        setAge(age);
        setSalary(salary);
    }

    public String getName() { return name; }
    public int getAge() { return age; }
    public double getSalary() { return salary; }

    public void setName(String name) {
        if (!name.isEmpty()) this.name = name;
    }

    public void setAge(int age) {
        if (age >= 18 && age <= 65) {
            this.age = age;
        } else {
            System.out.println("Invalid age. Must be between 18 and 65.");
        }
    }

    public void setSalary(double salary) {
        if (salary > 0) {
            this.salary = salary;
        } else {
            System.out.println("Salary must be positive.");
        }
    }

    public void displayInfo() {
        System.out.printf("Name: %s | Age: %d | Salary: %.2f%n", name, age, salary);
    }
}

public class Main {
    public static void main(String[] args) {
        Employee emp = new Employee("Riya", 28, 45000);
        emp.displayInfo();

        emp.setAge(70);         // Invalid – rejected
        emp.setSalary(-5000);   // Invalid – rejected
        emp.setSalary(50000);   // Valid – accepted
        emp.displayInfo();
    }
}

Output:

Name: Riya | Age: 28 | Salary: 45000.00
Invalid age. Must be between 18 and 65.
Salary must be positive.
Name: Riya | Age: 28 | Salary: 50000.00

Benefits of Encapsulation

  • Data Protection: Fields cannot be directly modified by external code.
  • Validation: Setters can enforce rules before accepting a value.
  • Flexibility: Internal implementation can change without affecting external code, as long as the public interface stays the same.
  • Maintainability: Bugs related to invalid data are caught in one place.
  • Loose Coupling: Classes interact through defined interfaces rather than internal details.

Summary

  • Encapsulation bundles data and methods into one class and controls access to the data.
  • Fields are declared private and accessed through public getters and setters.
  • Setters can include validation logic to ensure only valid data is stored.
  • Read-only fields have only a getter; write-only fields have only a setter.
  • Encapsulation improves data security, maintainability, and code flexibility.

Leave a Comment

Your email address will not be published. Required fields are marked *