Course contentsShow
← Java
Lesson 2465 of 2,87047. Java Platform Module System (JPMS)Free lesson

Strong Encapsulation: Modules vs Packages

Understand how modules provide stronger encapsulation than packages and what this means for accessibility.

Strong Encapsulation: Modules vs Packages

You'll learn how modules enforce stricter boundaries than traditional packages, fundamentally changing what "internal" really means.

The Package Problem

Before JPMS, Java's encapsulation was limited to public, protected, private, and package-private access modifiers. Here's the issue: any class with public visibility was accessible to the entire classpath. If you wanted to share classes within your library but keep them internal, tough luck—once they were public, anyone could use them.

Many libraries resorted to naming conventions like com.example.internal.* packages with warnings in Javadoc, but nothing enforced these boundaries. Developers could (and did) depend on internal APIs, creating fragile coupling.

How Modules Change Everything

Modules introduce strong encapsulation at a higher level than packages. With JPMS:

  • A package is not exported by default—it's completely invisible outside the module
  • Even public classes in non-exported packages are inaccessible to other modules
  • Only packages explicitly listed with exports in module-info.java become visible
  • This creates a clear contract: "These packages are my public API; everything else is truly internal"

Think of it this way: packages are like rooms in a house, and modules are like gated communities. Before JPMS, unlocked (public) rooms were accessible to anyone wandering the neighborhood. With modules, the entire community has a gate, and you explicitly decide which roads (packages) connect to the outside world.

The Practical Impact

You can now have public classes that serve as implementation details, shared across your module's packages but completely hidden from external modules. No amount of reflection or classpath manipulation can break this boundary without explicit permission (via opens or command-line flags).

Key Takeaway: Modules provide encapsulation at the package level, making it possible to hide public classes from the outside world—something packages alone could never achieve.