ashes999
ashes999

Reputation: 10163

How to avoid polluting API classes with internal methods?

Background:

TLDR: How can I indicate (or better yet, protect) my API's internal methods from being called by users outside my 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 only ever call SpriteComponent.dispose from my own classes in com.ashes999.*. I would never, ever expect (or even desire) that other users would directly call it; doing so would cause chaos, havoc, mayhem, and unmanaged resources to be disposed prematurely, causing crashes.

Upvotes: 3

Views: 379

Answers (1)

Eran
Eran

Reputation: 394146

A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)

At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same meaning. For members, there are two additional access modifiers: private and protected. The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

(Access control)

Upvotes: 4

Related Questions