Skip to content
Learn Netverks

Lesson

Step 14/36 39% through track

encapsulation

Encapsulation

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Encapsulation: the syntax, APIs, and habits you need before advancing in Java.

Teams ship Encapsulation on every Java codebase—skipping it leaves gaps in debugging and code reviews.

You will apply Encapsulation in contexts like: Spring Boot APIs, banking systems, Android (with Kotlin), and batch/data pipelines on the JVM.

Write Java with a public class (lessons use Main), click Run on server—the dev runner runs javac then java; fix compile errors from stderr (LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Encapsulation hides internal state behind methods—typically private fields with public getters/setters. This mirrors PHP visibility keywords but is idiomatic Java: never expose mutable fields publicly unless they are final value objects.

Access modifiers

  • private — class only
  • package-private (default) — same package
  • protected — subclass + package
  • public — everywhere

Getter/setter pattern

class Account {
    private double balance;

    public double getBalance() { return balance; }

    public void deposit(double amount) {
        if (amount > 0) balance += amount;
    }
}

Validate in setters—do not allow negative balances through a raw public field.

Important interview questions and answers

  1. Q: Why encapsulate?
    A: Preserve invariants, hide implementation, and reduce coupling for maintainability.
  2. Q: Are getters always needed?
    A: Prefer methods that express intent (deposit) over exposing raw mutable state.

Self-check

  1. Which modifier hides a field from other classes?
  2. Where should validation live—in the setter or the caller?

Pitfall: Exposing public mutable fields bypasses validation—use methods like deposit to enforce invariants.

Interview prep

Why private fields?

Encapsulation preserves invariants—callers use methods that validate input instead of mutating raw state that can break object rules.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • private fields why?
  • Getter always needed?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump