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

Encapsulation Enforcement on Module Path

Discover how strong encapsulation is enforced for modules on the module path but relaxed for classpath code.

Encapsulation Enforcement on Module Path

What you'll learn: You'll discover how Java's module system enforces strong encapsulation differently depending on whether code runs on the module path or the classpath.

The Enforcement Split

When you place modular JARs on the module path, the JPMS actively enforces the encapsulation rules you've declared in module-info.java. Non-exported packages are strictly inaccessible to other modules—even reflection attempts via setAccessible() will fail unless you've used opens. This is strong encapsulation in action.

However, when code runs on the classpath (the traditional, pre-JPMS way), Java relaxes these rules for backward compatibility. Classpath code lives in the "unnamed module," which can read all other modules and access their public types—even from non-exported packages. This relaxation allows legacy applications to continue working without immediate migration.

Why This Matters

Think of it like building security: modules on the module path are like apartments with locked doors (your exports and opens declarations control access). Classpath code is like the old building next door with open hallways—everyone can wander around more freely.

This design decision was intentional: the Java team wanted to introduce JPMS without breaking the vast ecosystem of existing libraries. Code gradually migrates to the module path, gaining encapsulation benefits, while classpath code maintains its traditional behavior.

Practical Implication

If you're building new applications, prefer the module path to leverage strong encapsulation. Your module-info.java declarations will be enforced, protecting internal implementation details. Legacy libraries can remain on the classpath until they're ready to modularize.

Key Takeaway: Strong encapsulation is strictly enforced for modules on the module path, protecting non-exported packages from unauthorized access, but relaxed for classpath code to maintain backward compatibility with pre-JPMS applications.