Java 9 – Modules (Next level of Encapsulation)

Encapsulation before Java 9

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

Here is the problem explained with code.

Calculator.Java

InternalAdditionProvider.java

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. There was no way to block it at compiler level. So below program will compile & run just fine.

Output:

How Java 9 modules solve this problem?

With Java 9, author of calculator-module library can restrict the access to InternalAdditionProvider at language 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

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.

Leave a Reply

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