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
ClassA
in package org.mylibrary
ClassB
in package org.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?
In Java, access modifiers are used to set the accessibility (visibility) of classes, interfaces, variables, methods, constructors, data members, and the setter methods. For example, class Animal { public void method1() {...} private void method2() {...} }
There are four access modifiers used in java. They are public, private, protected, no modifer (declaring without an access modifer).
Access modifiers are keywords that can be used to control the visibility of fields, methods, and constructors in a class. The four access modifiers in Java are public, protected, default, and private.
Encapsulation in Java would not be as effective as it is today without access modifiers. Access modifiers allow us to decide how parts of our classes can be accessed by other classes in other parts of our program. If we want a field or method to be accessible from anywhere, by any class, we can mark it as public.
It is difficult to give concrete advice since you give so little info about the roles of and relationship between ClassA
and ClassB
. However, one general solution (which is almost always used as part of eliminating dependencies) is to hide ClassB
behind an interface. Then ClassA
uses only that interface, so it is not anymore directly dependent on ClassB
. ClassB
can be made package private, its instances produced by e.g. a factory, or dependency injected into ClassA
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With