Skip to content

Strong encapsulation

Strong encapsulation is a core principle of the [[Java Platform Module System (JPMS)]] (also known as Project Jigsaw) introduced to enhance the integrity and security of the Java platform.^[100-inbox-java-jigsaw.md] It fundamentally changes how the Java runtime manages access to internal APIs by restricting access to the internal elements of the Java SE platform.

Purpose and Evolution

The primary driver for strong encapsulation was to secure the internal APIs of the Java platform.^[100-inbox-java-jigsaw.md] Historically, Java allowed developers to access and use internal, non-standard classes (such as those in sun.misc.Unsafe), which created significant maintenance burdens and security risks.^[100-inbox-java-jigsaw.md] By enforcing strong encapsulation, the platform aims to prevent developers from relying on these internal implementation details, which are subject to change or removal without notice.

Strong encapsulation ensures that modules in a modular application are strictly isolated from one another unless explicitly defined otherwise.^[100-inbox-java-jigsaw.md] This allows for better maintainability and performance optimizations within the JVM.

Impact on Developers

For many existing applications, the introduction of strong encapsulation presents a migration challenge.^[100-inbox-java-jigsaw.md] Code that previously relied on internal APIs—often referred to as "illegal access"—will fail at runtime or compile time unless specific flags or arguments are used to relax these restrictions.^[100-inbox-java-jigsaw.md]

To aid in the transition, Java provides flags such as --add-opens and --add-exports that allow developers to selectively expose specific packages to modules that require them, effectively "relaxing" the strong encapsulation for legacy or necessary integrations.^[100-inbox-java-jigsaw.md]

  • [[JPMS]]
  • [[Java modules]]
  • [[Modularity]]

Sources

^[100-inbox-java-jigsaw.md]