I am developing a java API. During my development, I keep facing the following issue:
I have two classes in two different packages. Class A in package x, and class B in package y. I need the class A to access a method M defined in class B. Hence, the modifier that should be used for the method M is public
. However, I do not want to allow the developer who will use my API in his/her java application to access the method M. The problem is that the method M has a public
modifier as I mentioned, and hence anyone can access it within the API or from outside the API. At the same time, if I decrease the modifier level of the method M to protected
or private
, the class A will not be able to access the method M because it belongs to a different package. How can I solve this problem? Is my only solution to have A and B in the same package?
Create an interface and expose only that to the public, hiding your implementation. For example:
My implementation (in say, for example, application.jar):
public class Test implements TestInterface {
public void somePrivateStuff() { }
public void somePublicStuff() { }
}
Dear world, here is my API (in say, for example, publicAPI.jar):
public interface TestInterface {
public void somePublicStuff();
}
Other developers would compile against your publicAPI.jar. The runtime implementation would come from your application.jar.
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