What is the use of the "export" clause in a module-info file in Java 9?

JavaObject Oriented ProgrammingProgramming

A Module is a combination of both code and data that has a name, declares dependencies on other modules, exports packages that contain the public types that can be accessible outside this module and specifies the services it uses or the service implementations it provides. All of these have specified in a module-info.java file, which is included in the root directory of a module.

There are two types of "export" clause can be used in "module-info.java" file.

1) export <package>: By default, the type public of a module is no longer visible outside the module. To make the public types of a given package visible from other modules, we must export this package. We must keep in mind that we are at the package level and not at the unit level of a type. But, sub-packages are not exported.

We need to allow other modules to use the classes and interfaces of the package tp.com.tutorialspoint.model, we can write as below:

module com.tutorialspoint.model {
   exports tp.com.tutorialspoint.model;

It's very important to understand that a package can only be present in only one module. Otherwise, we will get an error as below:

Error:(1, 1) java: package exists in another module:

2) export <package> to <module>: We can strengthen the security of our modules by reducing the visibility of certain packages to a finite list of modules: only the modules listed will be able to access these classes.

module com.tutorialspoint.model {
   exports tp.com.tutorialspoint.model
      to com.tutorialspoint.gui;
Published on 28-Apr-2020 17:36:29