The exports Directive: Controlling Package Visibility
What you'll learn: How to use the exports directive in module-info.java to make specific packages accessible to other modules while keeping everything else private.
By default, all packages in a module are hidden from other modules. Even if another module declares requires on your module, it still can't access any of your code unless you explicitly permit it. The exports directive is how you grant that permission.
How exports Works
In your module-info.java, you list which packages should be visible to other modules:
module com.example.library {
exports com.example.library.api;
// com.example.library.internal remains hidden
}
In this example, only the com.example.library.api package is accessible to other modules. Any other packages in your module (like com.example.library.internal) remain strongly encapsulated—completely invisible and inaccessible to the outside world.
Why This Matters
Think of a module like a building with many rooms. Without exports, all the doors are locked. The exports directive unlocks specific doors (packages) so visitors (other modules) can enter, while keeping private rooms sealed.
This enables true implementation hiding. You can refactor internal packages, change private APIs, or reorganize code without breaking external consumers—because they never had access to those parts in the first place.
Basic Syntax
module my.module {
exports my.public.package;
exports another.public.package;
}
Each exports statement makes one package accessible to all other modules that requires yours.
Key Takeaway: The exports directive explicitly makes a package accessible to other modules, while non-exported packages remain completely private—this is the foundation of strong encapsulation in JPMS.