This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
Public Methods in Non Public Classes
Posted by M Nelson on January 16, 2001 at 4:19 PM
In many cases, it is valuable for a package to expose a public interface without exposing the details of how the interface is implemented. For example, some of our applications have a "persistence" package. This package contains: 1. A public interface that declares a set of methods for saving and retrieving objets to and from persistent storage. 2. Some classes which have only package access that implement the public interface with public methods. 3. A public class which implents the factory pattern. This class has public methods that allow classes in other packages to request an instance of an object that implements the public interface. When objects in the application want to save data, they ask the factory (a public class) for an instance of a class which implements the (public) interface. The factory can construct a new instance of the (package scope) concrete class that implements the interface, and return it to the requesting class. The requesting class is restricted from relying on any knowledge of what specific implementing class is being returned. Since the concrete classes in the persistence package are package visible only, the calling class cannot create instances of them directly. They have to ask the public factory for an instance. This enforces an abstraction that is very valuable. If we want to install a different version of our application that uses filesystem files instead of a database to save data, we can modify the factory to instantiate and return a different set of classes that implement the public interface. Since the actual concrete classes in the package are only visible within the package, we can rely on the assumption that we can replace them without any other code having to change. As long as the new classes implement the public interface, they can be substitued, and the other classes don't even know they have changed. :-) Mark
Replies:
|