I’m developing a library which the other programmer will import and use it for their purposes.
I’m confused about the objective of Java access modifier.
The problem is that I have classes below
ClassAin packageorg.mylibraryClassBin packageorg.mylibrary.internal
ClassA needs to resolve ClassB so ClassB need to be public class.
However, from library user view, I don’t intend ClassB to be visible outside my library. Because it shouldn’t be and don’t need to be initiated by the user.
I think of moving ClassB to package org.mylibrary and make it package-private class.
If I move it to the same package, it would be a mess and difficult to organize because I have many classes in this scenario so there will be many .java files in a big one package.
Normally I put the classes in packages grouped by category or layer and I think it’s easy to organize.
How do I do this? How do people handle this problem?
It is difficult to give concrete advice since you give so little info about the roles of and relationship between
ClassAandClassB. However, one general solution (which is almost always used as part of eliminating dependencies) is to hideClassBbehind an interface. ThenClassAuses only that interface, so it is not anymore directly dependent onClassB.ClassBcan be made package private, its instances produced by e.g. a factory, or dependency injected intoClassA.