4

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?

ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155
Sagar Pudi
  • 4,634
  • 3
  • 32
  • 51
  • 3
    Do you mean unless that package is exported? Could you quote an illustration of what exactly as do you see changing in terms of accesses and where? – Naman Nov 15 '17 at 06:59
  • @nullpointer, I missed the point. Yes, In case of when we do not export the module explicitly. – Sagar Pudi Nov 15 '17 at 07:03

2 Answers2

4

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.

Naman
  • 27,789
  • 26
  • 218
  • 353
3

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.

ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155