beginnerFree

Encapsulation

Private fields + public methods = controlled access

Encapsulation

Encapsulation hides internal data and exposes it only through methods.

The narrated version of this skribble — tap play for the full-size video.

0:00 / 2:20

The Big Picture

Encapsulation hides internal state behind private fields and public methods. Protects invariants and decouples impl.

  • "Black box" design - users don't see internals
  • Prevents invalid state (negative age, null fields)
  • Allows changing internals without breaking clients

Foundation of maintainable, safe code.

How It Works

The compiler enforces access modifiers: private, protected, package-private, public. Reflection can bypass (opt-in).

  • Getters/setters provide controlled access
  • Immutable classes (final fields) maximize safety
  • Defensive copies prevent reference leaks
  • JVM also performs access checks at runtime

In the Java Landscape

JavaBeans convention uses get/set method naming.

  • Records (Java 16+) auto-generate accessors
  • Lombok @Getter/@Setter reduces boilerplate
  • Modules (Java 9+) encapsulate entire packages
  • Sealed classes restrict who can subclass/implement a type
  • Builder pattern for complex object construction

Pitfalls and Best Practices

  • Default to private, widen only when needed
  • Return copies of mutable collections, not originals
  • Validate in setters: throw IllegalArgumentException
  • Avoid public fields except constants (static final)
  • Use builder pattern for complex construction
#java#oop#encapsulation