Sub topic 2
Strong Encapsulation: What `public` Really Means Now
Assume you know Java packages, access modifiers, JAR files, and basic reflection. In the Java Platform Module System (JPMS), public controls access inside an exported package. A public class in a non-exported package is not part of another module's accessible API.
Public Requires an Export
A module descriptor controls which packages other modules can read. This descriptor exports only the API package:
module com.example.library {
exports com.example.library.api;
}Classes in com.example.library.api can be used by readable modules. Public classes in com.example.library.internal remain hidden. This gives a module a smaller public surface and allows its internal implementation to change.
Compiling and Running on the Module Path
The module path is the module-system equivalent of the classpath. Suppose src contains module directories:
src/
├── com.example.library/
│ └── module-info.java
└── com.example.app/
└── module-info.javaCompile and run the application module like this:
javac -d out --module-source-path src -m com.example.app
java --module-path out -m com.example.app/com.example.app.MainThe compiler checks both dependency declarations and exported packages. The runtime checks the module graph again.
The Modular JDK and `java.base`
The JDK is divided into named modules. Every named module implicitly reads java.base, which contains packages such as java.lang, java.util, and java.io. Therefore, you do not write requires java.base;.
Implied Readability
Use requires transitive when a dependency appears in your module's public API:
module com.example.library {
requires transitive java.sql;
exports com.example.library.api;
}A module requiring com.example.library can also read java.sql. Use this carefully because it exposes a dependency to downstream modules.
Qualified Exports
A qualified export limits access to named modules:
exports com.example.library.internal
to com.example.library.tests;Only com.example.library.tests can access that package. This is useful for testing or tightly controlled integration.
Reflection and `opens`
Reflection can inspect members at runtime, but deep reflection into private members requires an open package:
module com.example.library {
opens com.example.library.model;
}opens allows runtime reflection but does not grant ordinary compile-time access. You can also open a package temporarily with --add-opens.
Exercise
Can another module compile against a public class in a package that is not exported?
Show answer
No. The class is public, but its package is not accessible across the module boundary.