Lesson 15 of 25

Encapsulation

Access Modifiers and Getters/Setters

Encapsulation hides internal data and provides controlled access through getters and setters.

Example
public class BankAccount {
    // Private fields — hidden from outside
    private String owner;
    private double balance;

    public BankAccount(String owner, double initialBalance) {
        this.owner = owner;
        this.balance = initialBalance;
    }

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

    // Controlled setter with validation
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public boolean withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            return true;
        }
        return false;
    }
}

BankAccount acc = new BankAccount("Alice", 1000);
acc.deposit(500);
acc.withdraw(200);
// acc.balance = -999; // Error! balance is private

Access Modifier Levels

Java has four access levels that control visibility.

  • public — accessible from anywhere
  • protected — accessible within package and subclasses
  • default (no modifier) — accessible within package only
  • private — accessible within the class only