Modules   «Prev  Next»

Purpose of Modules

A module is a named, self-describing collection of code and data. Its code is organized as a set of packages containing types, i.e., Java classes and interfaces; its data includes resources and other kinds of static information.
From this definition, we get that a module is just a set of compiled Java code and supplementary resources that are organized in a predefined structure. If you already use Maven multiple modules
  1. Maven or
  2. or Gradle multiproject builds
to organize your code, then you can easily upgrade each of these Maven modules or Gradle projects to a JPMS module. Each JPMS module should have a name that follows the same naming convention as Java packages; that is, it should use the reverse-domain-name pattern—for example, com.mycompany.mymodule. A JPMS module is described using the file module-info.java in the root source directory, which is compiled to module-info.class. In this file, you use the new keyword module to declare a module with a name.
A module is a set of packages designed for reuse.

This is a long overdue building block in the Java language. In effect, modules record the structure of your program so that the packages
  1. you want to be reused can be reused
  2. while the packages you don't want to be reused can't be reused.

A program built of modules will be more reliable than a program built from a loose set of packages in jar files that can access each other freely and are exposed to too many APIs in the outside world.
In other words, in JDK 9
programs are modules.

Here is a module that everyone will soon be familiar with known as java base.

Java Base
Java Base

java.lang.object root of every Class

It is the foundation of every Java program like java.lang object is the root of every class.
java.lang.object
  1. Blue: In blue, are the packages of java.base intended for use by code outside the module these are its exported packages
  2. Red: In red are the packages internal to java.base.

Declaring Module

They can be used by code inside the module but not by code outside the module. These are its concealed packages. A module is declared in a new kind of file called module-info.java.
It gives the name of the module and its exported packages. By exporting the java.lang package, it means that the public classes of java.lang are accessible from outside java.base and a package that is not explicitly exported, such as
com.sun.crypto.provider
is concealed. Its public classes are not accessible outside Java base. This is the first feature of modules in JDK 9, namely strong encapsulation.