It is a problem in Java that you have to make a method "public" in order to use it outside the package*. There is no such concept as "friend" methods like in C++. Unfortunately this means that anyone else could call the public method, not just from classes in other packages within your own code, but from anyone else's code. There is no way within the language to enforce access to only from within your own code.
I would suggest you do the following:
- Choose one or two packages in your project to designate as your public API. Within these packages, make a conscious decision which classes and methods that you wish to be called by others. The only public classes and methods in this package should be those you want visible by others. Write good Javadoc for the public API.
- Use default (package protected) access for everything else within your public API packages.
- You generally will have other "helper" packages within your code, that are only for internal use by your public API packages. These packages would have classes and methods that would need to be visible from the classes in your public API. Therefore they are required to use the "public" keyword. However, you don't want 3rd party code to use these public classes/methods directly. The solution? Do not publish Javadoc for those packages! Nobody else even will even know they exist.
*There is also "protected" access for subclasses -- this should only be used for classes that you have designed and documented to be extended as part of your public API. [ March 07, 2005: Message edited by: Geoffrey Falk ]
Sun Certified Programmer for the Java 2 Platform
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop