1. Introduction
In this tutorial, we’ll discuss the accessibility of classes within a module. We’ll discuss different cases with the help of public
class in a module and accessing this class from another module. For this tutorial, the two modules are moduleA
and moduleB
. The two packages are pack1
and pack2
. pack1
is in moduleA
and pack2
is in moduleB
.
Following is the file structure of moduleA
and moduleB
for intelliJ on my machine:
D:.
│ .gitignore
│ moduleA.iml
│
└───src
│ module-info.java
│
└───pack1
Message.java
D:.
│ .gitignore
│ moduleB.iml
│
└───src
│ module-info.java
│
└───pack2
Test.java
The code of Message.java
:
package pack1; public class Message { public void hello(){ System.out.println("Hello"); } }
The code of Test.java
accessing Message.java
:
package pack2; import pack1.Message; public class Test { public static void main(String[] args){ Message message = new Message(); message.hello(); } }
Module descriptor of moduleA:
module moduleA{ exports pack1; }
Module descriptor of moduleB:
module moduleB { requires moduleA; }
2. Case 1: A public class in a module can’t be accessed by another module if current module doesn’t export the package
To validate this, comment exports pack1
in module descriptor of moduleA
.
module moduleA{
//exports pack1;
}
In this case you’ll get following error at compile time:
Package ‘pack1’ is declared in module ‘moduleA’, which does not export it to module ‘moduleB’.
Note that the Message.java
is public
but still can’t be accessed because the package pack1
is not exported.
3. Case 2: A module can’t access another module’s public class if the module doesn’t ‘requires’ the module of public class
To try this, comment requires moduleA;
in module descriptor of moduleB
.
module moduleB {
//requires moduleA;
}
In this case you’ll get following error at compile time:
Package ‘pack1’ is declared in module ‘moduleA’, but module ‘moduleB’ does not read it.
Note that the package pack1
of class Message.java
is exported and class is public but still can’t be accessed by moduleB
. The reason is moduleB
does not specify dependency on moduleA
.
4. Conclusion
To read a class from another module:
- The module of accessed class should export the package of the class.
- Accessing module should add dependency on the class’ module using
requires
.