Sub topic 6
Strong encapsulation: what `public` really means now
Assume you know Java packages, access modifiers, interfaces, reflection, and basic javac and java commands. This chapter explains how the Java Platform Module System (JPMS) adds a boundary around packages.
In ordinary Java code, public means that code in other packages can access a type. With modules, public is necessary but not always sufficient. A public type is accessible across module boundaries only when its package is exported and the caller's module can read the module that contains it.
Public does not mean exported
Consider this module:
module com.example.library {
exports com.example.library.api;
}
package com.example.library.api;
public class Book {
public String title() {
return "Java Modules";
}
}Code in another readable module can use Book because its package is exported.
Now consider another class:
package com.example.library.internal;
public class BookParser {
public static BookParser create() {
return new BookParser();
}
}BookParser is public, but its package is not exported. Code in another module cannot import it. The module descriptor hides the entire package from normal compile-time and run-time access.
This lets a library expose stable interfaces while changing implementation classes without promising compatibility.
| Java declaration | Package exported? | Accessible to another named module? |
|---|---|---|
| `public` type | No | No |
| `public` type | Yes | Yes, if the caller reads the module |
| package-private type | Yes | No |
| `private` member | Yes | No normal access |
Readability and accessibility work together
Two conditions must hold:
- The target type must be
public. - Its package must be exported by the target module.
The caller must also declare requires com.example.library;. This creates readability. Readability lets the caller refer to the target module, while exporting makes selected packages accessible.
Strong encapsulation and reflection
Strong encapsulation also affects reflection. Code cannot freely use deep reflection to inspect private members or access non-exported packages in named modules. For example, calling setAccessible(true) may fail with InaccessibleObjectException.
If a framework needs reflective access, the module can use opens:
module com.example.library {
exports com.example.library.api;
opens com.example.library.model;
}exports supports normal Java access. opens supports run-time reflection. An opened package does not automatically become importable by other modules.
Exercise
A public class is in com.example.library.internal, and the module exports only com.example.library.api. Can another named module import the class?
Show answer
No. The class is public, but its package is not exported. The caller also cannot import it merely because it declares requires on the library module.