Java 9 scope of public access specifier

Java 9 scope of public access specifier has been changed. Because of a modular system in java public access specifier scope has been changed. Its little bit interesting let see here for more details with an example about how its will behaves in Java 9.

Scope of public access specifier

Java 9 on words if any class is public it doesn’t mean that class can be accessible everywhere. Accessibility of public class depends on module declaration and based on module declaration there are three possible scenarios as below:

public only within a module

public to everyone

public but only to the specific module

1. public only within a module:

public only within a module means that public class can only accessible in within module in other words public class cannot be an accessible outside of the module.

When modules are not exporting package inside module declaration means class inside those packages will be accessible by other modules.

Example:

module com.developer.foo is not exporting any package means that every public class inside that module cannot be accessible by outside of the module.

module com.developer.foo{
}

2. public to everyone:

public to every module means that class can be accessible to every reader modules. It’s possible only when source module export those package, so public class available in that package can be accessible by reader modules.

Example:

we have two module com.developer.foo and com.developer.boo whose module-info.java as under:

module : com.developer.foo

here com.developer.foo module is exporting com.developer.service package for other modules. Reader modules can access public class of com.developer.service packages.

module com.developer.foo{
exports com.developer.service; // foo is exporting so it public class is can be accessible by other modules
}

module : com.developer.foo

Here module foo can access all public class which is insidecom.developer.service package because foo module is exporting that packages.

3. public but only to specified module

In above example, we have seen that com.developer.service can be accessible every reader modules but we can allow to access to the specific module instead of all module with the export [ package-name ] to [module1,module2] option during module declaration.

Example:

We have three modules,com.javadeveloper.foocom.javadeveloper.boo, com.javadeveloper.zoo, Here are module-info.java files.

JavaDeveloperZone is the group of innovative software developers. We are expert in Java JEE and BigData application development. Our contributions will help Java developers and make development journey easy. Feel free to ask any question and suggestion. Always have space for improvement !
We are also providing software application development as service. Contact us