Public Types in Non-Exported Packages Are Inaccessible
What you'll learn: You'll understand why public classes in packages that aren't explicitly exported remain invisible to other modules—a fundamental shift from traditional Java visibility.
The Core Principle
In pre-JPMS Java, a public class was accessible from anywhere. JPMS changes this: module boundaries override access modifiers. Even if a class is declared public, if its package isn't listed in an exports directive, that class is completely invisible to code in other modules.
Think of it like a building with public rooms: even if a room is labeled "public," it doesn't matter if the entire floor isn't open to visitors. The floor-level restriction (the module export) takes precedence.
How It Works
// module-info.java in module com.example.library
module com.example.library {
exports com.example.api;
// com.example.internal is NOT exported
}
// In package com.example.internal (same module)
package com.example.internal;
public class Helper { // public, but hidden!
public void doWork() { }
}
From another module, Helper cannot be accessed—not through imports, not through reflection, not at all. The compiler will act as if Helper doesn't exist. This is strong encapsulation: you control exactly which packages form your module's public API.
Why This Matters
This design lets you refactor internal implementation freely without breaking external code. Your module's contract is only what you explicitly export. Everything else is truly private to the module, regardless of Java visibility modifiers.
Key Takeaway: In JPMS, public visibility is necessary but not sufficient for cross-module access—the package must be exported in module-info.java, or the type remains hidden.