Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between no access specifier and public in java 9 module?

From java 9, public access is limited to it's own module. Does it mean public acts like a package protected ( no access specifier )? Can someone clarify this?

like image 893
Sagar Pudi Avatar asked Mar 07 '23 14:03

Sagar Pudi


2 Answers

One of the primary goals of the Module system is to provide :

Strong encapsulation, to allow a component to declare which of its public types are accessible to other components, and which are not.

To add to the #accessibility aspect of it -

The Java compiler and virtual machine consider the public types in a package in one module to be accessible by code in some other module only when the first module is readable by the second module, in the sense defined above, and the first module exports that package

So, in order to access the public types of a package as well from another module, the accessed module needs to export that package to make it readable.

But then this wouldn't necessarily be true for all types of modules ( e.g. automatic modules) in the module system.

Does it mean public acts like a package protected ( no access specifier )?

No, the public types shall be accessible to different packages within the same modules as well as when(if) exported, the package exposes the access to the public types by other packages of other modules as well.

like image 85
Naman Avatar answered Mar 10 '23 02:03

Naman


package elements are only accessible within the package. Other packages in the module have no access to these elements.

public without exports are accessible to any other packages in the module.

In other words:

  • package elements are package-local
  • public without exports are module-local.

So, public without exports is wider than package.

like image 21
ZhekaKozlov Avatar answered Mar 10 '23 03:03

ZhekaKozlov