How to avoid polluting API classes with internal methods?
Background:
- In C #, you can have methods
internal
that are assembly bound (JAR) - Internal methods can be called by other classes in this assembly, but not outside.
- Java has no such counterpart.
- When creating an API, my internal methods must be public, so other parts of my API can call them.
- This pollutes my API and potentially allows users to call internal methods.
TL; DR: How can I specify (or better yet, protect) my internal API methods from being called by users outside of the API classes, given that the methods are public?
Typical example:
// public class in com.ashes999.components
class SpriteComponent {
// This method should be internal
public void dispose() { ... }
}
// public class in com.ashes999.management
class SceneManager {
public void changeScene(Scene s) {
for (SpriteComponent s : this.allEntities.allSprites) {
s.dispose();
}
}
}
I would SpriteComponent.dispose
only name my own classes in com.ashes999.*
. I would never have expected (or even wished) for other users to name it directly; this will lead to premature removal of chaos, chaos, chaos and unmanageable resources, leading to disruptions.
source to share
A class can be declared a public modifier, in which case this class will be visible to all classes. If a class does not have a modifier (also called package-private by default), it is only visible within its own package (packages are called groups of related classes - you will learn about them in a later lesson.)
At the member level, you can also use a public modifier or no modifier (private-package) like top-level classes, and with the same meaning . There are two additional access modifiers for members: private and secure. A private modifier indicates that a member can only be accessed in its class. The protected modifier indicates that a member can only be accessed within its own package (as with private-private) and also by subclassing its class in another package.
( Access Control )
source to share