Hiding classes in a jar file
I'm understanding you're not looking to hide the actual classes, just prevent their construction outside a factory class. This I think can be quite easily achieved by using package private (default) visibility in the class constructors. The only limitation is that you'll need to have the classes and the factory in the same package so in a medium to large codebase things may get unnecessarily complex.
If I understand your question correctly, you would like to make sure that users of your library are forced to use your factory to instantiate their objects rather than using the constructors themselves.
As I see it there are two possibilities, one of which is silly but usable in few, specific cases, and the other one is the most practical and probably most commonly used way of doing it.
- You could make all your classes into private inner classes of the factory. This would work if you had one factory per class, but is hardly workable if you have a lot of different classes being managed through one factory.
- You could use the
protected
access modifier to restrict access to your class constructors. This is common practice when using the factory pattern.