Search code examples
javapackagesemanticsaccess-modifiers

Organizing project via Java packages and access modifiers for "project internal vs public" functions


I am working on a project that is best organized by at least two packages. For example, com.mycompany.core and com.mycompany.ui. The "core" package wants to expose certain functions to just the "ui" package, without exposing it to the outside world.

For example, I have a Point class in the "core" package, where it is efficient for me to allow my "ui" package to move a point via a movePoint(int dx, int dy) method of the Point class. However, I don't want the outside world to have the ability to modify a point via this method.

Can this be accomplished cleanly without any convoluted code? I realize that Java doesn't have the "friend" semantics of C++, but am I misunderstanding something about Java?

In a nutshell, even if I have two "related" packages in Java ("core" and "ui") as above, as far as Java is concerned, they might as well be complete strangers to each other? There is no way (without convoluted code) to give the "ui" package special treatment over any other random package that is simply using my "core" and "ui" packages?

Thanks.


Solution

  • Basically, no. Each package in current Java is entirely standalone, a.b.c has no special relationship to a.b.d. So if my.code.api can access my.code.internals, anyone can.

    Java 9, via project jigsaw, is adding a new construct called a module that addresses this issue. Or you could use OSGI, which uses bundles to much the same effect.