Java 9 – Modules (Next level of Encapsulation)

Encapsulation before Java 9

  • Private – Encapsulates method/variable within class. Not accessible outside of class.
  • Default – Encapsulates method/variable within package.
  • Protected – Encapsulates method/variable within package & sub classes.
  • Public – Accessible everywhere.
  • Selectively public – What if we want method/variable accessible everywhere only within the project (API/library) but not to anyone else outside using this project as dependency? –  No Option (Till Java 9)




Here is the problem explained with code.

Calculator.Java – We want others to use this class to do addition. Internally this class will use InternalAdditionProvider.java.

InternalAdditionProvider.java – This is internal class in internal package & we don’t want others to use this class directly except Calculator.java. Actually we want to enforce it.

Before Java 9, we can use calculator-module jar/dependency in any project & can access Calculator.add() as well as InternalAdditionProvider.add() directly even thought author doesn’t expect it. Author can try to put everything in one package & try using package level encapsulation but that would take away freedom of logical structuring. WIth given package structure, there was no way to block it at compiler level.

So below program will compile & run just fine even though it is using InternalAdditionProvider.java

Output:

How Java 9 modules solve this problem?

With Java 9, author of calculator-module library can restrict the access to InternalAdditionProvider at compiler level itself & make sure no one uses it directly. To do this, author will have to add module-info.java

Below is the code for module-info.java

As per module-info.java code, only com.itsallbinary.calculator is exported i.e. other packages won’t be exported & allowed outside. Now after doing this, lets see what happens to our client code which directly tries to use InternalAdditionProvider.

Compiler error:

Conclusion:

So now authors of libraries have encapsulate code with more control & in precise manner without losing freedom of project structure inside library itself.

This is a basic example to explain modules. To get more in-depth details on module, refer https://www.oracle.com/corporate/features/understanding-java-9-modules.html

Leave a Reply

Your email address will not be published. Required fields are marked *