Modularity in Java
In short: Modularity means splitting a program into clearly delimited, replaceable building blocks (modules). Java has had its own module system (JPMS, Project Jigsaw) since version 9.
In more detail: Packages organize classes, modules bundle packages. A module states in a file module-info.java what it requires (requires) and what it offers to the outside (exports). Everything else stays invisible, even if it is public.
In Depth
// module-info.java
module com.example.shop {
requires java.sql; // needs the JDK module java.sql
requires transitive com.example.core; // passes this dependency on to users
exports com.example.shop.api; // only this package is usable from outside
opens com.example.shop.model to com.fasterxml.jackson.databind; // allow reflection
}Levels at a glance: class → package → module → JAR/application.
- Strong encapsulation: Even
publicis not enough if the package is not exported. This protects internal classes from misuse. - Reliable configuration: If a required module is missing, startup fails immediately with a clear message instead of later with
ClassNotFoundException. - Modular JDK: The JDK itself consists of modules (
java.base,java.sql,java.net.http…).java.baseis needed by everyone and included automatically. Withjlinkyou create a slimmed runtime containing only the needed modules. - Classpath vs. module path: Old libraries without
module-infokeep running on the classpath or as “automatic modules”. - Practice: Many projects still use only Maven or Gradle modules (without JPMS). That divides the build into subprojects but does not enforce visibility at runtime.
- Why modular? Clarity, replaceability, separate tests, clear responsibility, less “spaghetti”.
- In general: The principle applies beyond Java: modules, packages, microservices and libraries are all forms of modularity.
See also: Packages/API, Core, Access modifiers