Skip to content

Chapter 14 of 37

Encapsulation and Access Modifiers

Protect invariants with private, package, protected, and public boundaries.

30 minutes 10 quick checksBy Subha Prasad
Lesson 14 of 37Course navigation

Lesson content

Read, practise, then check your understanding

Encapsulation hides representation behind operations that maintain valid state. private is narrowest, no modifier gives package-private access, protected adds subclass access under specific rules, and public exposes an API wherever its type is visible.

Preserve invariants

public final class Percentage {
    private final double value;

    public Percentage(double value) {
        if (value < 0 || value > 100) {
            throw new IllegalArgumentException("0..100 required");
        }
        this.value = value;
    }

    public double value() { return value; }
}

Do not create setters mechanically; expose meaningful domain operations. Make defensive copies of mutable inputs and outputs, or use immutable types. Package-private helpers support cohesive internal collaboration without becoming public contracts. Protected fields couple subclasses to representation, so prefer private state with protected behavior. Keep APIs minimal, stable, documented, and free of implementation types that would prevent future refactoring.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes private?
Which Java term matches this description: Access limited to the declaring top-level nest.
Which statement best describes package-private?
Which Java term matches this description: Access within the same package when no modifier is written.
Which statement best describes protected?
Which Java term matches this description: Package access plus access for subclasses under protected rules.
Which statement best describes public?
Which Java term matches this description: Access permitted wherever the declaring type is accessible.
Which statement best describes encapsulation?
Which Java term matches this description: Protecting invariants behind a small intentional API.

0 of 10 checks passed

Your progress is saved on this device.

Encapsulation and Access Modifiers | Java Lesson | Subha Prasad