Modules   «Prev  Next»

What is a Module in JDK 9?

A module isn't just a set of packages, it is a set of exported and concealed packages. The public classes of exported packages are accessible outside the module, the public classes of concealed packages are not accessible outside the module. This means that access control is more powerful in JDK 9 than in JDK 8. Furthermore, you may set up modules to encapsulate your own code.

Compare Accessibility JDK 8 versus JDK 9
Compare Accessibility JDK 8 versus JDK 9

In JDK 9 you can arrange for public classes to be accessible to everyone or accessible only to other classes in the same module or sort of a halfway house where they are accessible to classes in the same module and a limited set of friend modules.

What does public mean in JDK 9?

So if we are looking at public on a class declaration it no longer means that everyone can access the class.
Access depends on whether the class's module exports the class's package.

java.base Module example

Since java.base is a module, let us reuse it with the module of our own. Here is a class in the
package com.example.hello
a simple class, and let us declare a module for it. hello.world at the bottom in module in photo Java.
For the sake of argument, let us export the calm example hello package with the exports directive. Now you are probably wondering, how the hello world module knows that it has a package called

com.example.hello 
.
After all, nothing in the package seems to point to the hello.world module. It is up to the tooling to decide during developments which module each package belongs to. In practice, your IDE will take care of it. You will create a modular java application and be asked the name of the module.
Hello World Module
Hello World Module

javac command figures out the correct module

Every package you create will be part of the designated module. If you run javac by hand, then javac figures out which module each package is in. That is why module-info.java is at the same level as the com directory. In other words, if module-info.java is at the same level as the package hierarchy, then javac treats all those source files as one module. The benefit of relying on tooling to decide module membership is that it is really easy to place an existing package in a module and immediately give that package the benefit of strong encapsulation. We do not want each and every class like say hello, to have to opt in by declaring the module it belongs to. That would invite errors, such as classes in the same package trying to join different modules and this is undesireable for reasons I will mention later.

The
public class SayHello 
imports the java.lang package.