Sagar Pudi
Sagar Pudi

Reputation: 4824

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?

Upvotes: 4

Views: 126

Answers (2)

Naman
Naman

Reputation: 32028

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.

Upvotes: 4

ZhekaKozlov
ZhekaKozlov

Reputation: 39594

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.

Upvotes: 3

Related Questions