Skip to main content

Beginner-Friendly Topic

Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!

Lesson 3 of 10

Encapsulation & Access Modifiers

Encapsulation means hiding internal implementation details and exposing only what is necessary through a controlled interface (public methods). It protects data integrity - no external code can put an object into an invalid state. Access modifiers (private, public, protected, package-private) are encapsulation's enforcement mechanism.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Access Modifier Rules

  • private - accessible only within the same class. Fields should almost always be private.
  • package-private (no modifier) - accessible within the same package. Avoid for field access.
  • protected - accessible in the same package AND all subclasses.
  • public - accessible from anywhere. Methods forming your API are public.
  • Best practice: fields private + public getters/setters = encapsulated class
  • Prefer immutability: if a field needn't change after construction, make it private final and skip the setter.

Encapsulation Enforcing Invariants

Encapsulation Enforcing Invariants
public class BankAccount {
    private final String accountNumber;  // immutable - set once
    private double balance;              // private - protected from direct modification
    private String ownerName;

    public BankAccount(String accountNumber, String ownerName, double initialDeposit) {
        if (initialDeposit < 0) throw new IllegalArgumentException("Initial deposit can't be negative");
        this.accountNumber = accountNumber;
        this.ownerName     = ownerName;
        this.balance       = initialDeposit;
    }

    // No setBalance(double) - balance can ONLY change through deposit/withdraw
    // This enforces the business rule: only valid operations change balance

    public void deposit(double amount) {
        if (amount <= 0) throw new IllegalArgumentException("Deposit must be positive");
        this.balance += amount;
        System.out.printf("Deposited $%.2f. New balance: $%.2f%n", amount, balance);
    }

    public void withdraw(double amount) {
        if (amount <= 0)         throw new IllegalArgumentException("Withdrawal must be positive");
        if (amount > balance)    throw new IllegalStateException("Insufficient funds");
        this.balance -= amount;
        System.out.printf("Withdrew $%.2f. New balance: $%.2f%n", amount, balance);
    }

    // Getters - controlled read access
    public String getAccountNumber() { return accountNumber; }
    public double getBalance()       { return balance; }
    public String getOwnerName()     { return ownerName; }

    @Override
    public String toString() {
        return String.format("Account[%s, owner=%s, balance=$%.2f]",
                              accountNumber, ownerName, balance);
    }
}

Quick Quiz

Tip

Tip

Practice Encapsulation Access Modifiers in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Encapsulation & Access Modifiers

Practice Task

Note

Practice Task - (1) Write a working example of Encapsulation Access Modifiers from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Encapsulation Access Modifiers is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.

Key Takeaways

  • Encapsulation means hiding internal implementation details and exposing only what is necessary through a controlled interface (public methods).
  • private - accessible only within the same class. Fields should almost always be private.
  • package-private (no modifier) - accessible within the same package. Avoid for field access.
  • protected - accessible in the same package AND all subclasses.

Topics in This Module

0/10 done