OOP: Encapsulation & Access

☕ Java Lesson 11 Intermediate

Encapsulation is one of the four main pillars of OOP. It refers to bundling data fields and behaviors into a single class unit and restricting direct access to prevent corruption.

1 Access Modifiers & Data Hiding

Java supports four levels of access modifiers to control visibility:

  • private: Access is restricted strictly to the declaring class. Highly recommended for instance variables.
  • default (no keyword): Package-private. Accessible only inside the same package folder.
  • protected: Accessible in the same package and by child subclasses in other packages.
  • public: Open and accessible from any package.
2 Getters, Setters, and Validation

To expose private fields safely, we write **Getter** (retrieval) and **Setter** (modification) methods. Setters allow us to validate values before committing changes, preventing invalid data states (like negative balances or ages).

Java — OOP Encapsulation ▶ Run Code
class BankAccount {
    private String owner;
    private double balance;

    BankAccount(String owner, double initialBalance) {
        this.owner = owner;
        setBalance(initialBalance); // Use setter for safe validation
    }

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

    // Setter with input guard validations
    public void setBalance(double balance) {
        if (balance >= 0) {
            this.balance = balance;
        } else {
            System.out.println("Error: Negative balances are not permitted!");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount("Alice", 500.0);
        System.out.println("Initial Balance: $" + account.getBalance());
        
        // Try invalid update
        account.setBalance(-200.0);
        System.out.println("Balance remains: $" + account.getBalance());
    }
}
3 Code Challenge
Challenge: Design a class named `Employee` with private fields: `name` and `salary`. Provide a constructor, getters, and setters. Inside the `setSalary(double salary)` method, add a validation check that rejects any salary update below 1000. Test this validation in `main()` with correct and incorrect salary attempts.