Java Modularity

New functionality of Java modules was introduced as part of Java 9. Java Modules contain packages which are by default private. But why it is so?

It is introduced to improve maintainability of code as well as restricted accessibility.

So every module, has an module_info descriptor file apart from the packages.

module_info file has the configuration whether those included packages can be exposed and be made public so that other modules can access it.

Exporting Modules:

Every package is private inside a module but module_info file can make it public
using export statement as below.

module my.module {

export package.name;

}

We can restrict which modules have access to our APIs using the exports…to directive.

Similar to the exports directive, we declare a package as exported. But, we also list which modules we are allowing to import this package as a requires. Let’s see what this looks like:

module my.module {
export com.my.package.name to com.specific.package;
}

Module Requires:

A different module which wants to have access to above module package uses requires
keyword as below.

module my.module {

requires module.name;

}

Module Uses:

Now consider, If there is an interface and it’s implementation under same module.

So in the module info file for that module, it would be declared as this.

module my.first.module { provides MyInterface with MyInterfaceImpl; }

The same can be used in another module using uses keyword in the modue_info of the dependent module.

module my.second.module { uses MyInterface; }

If you see in the module info above, we have interface name instead of implementation which should be more than enough.