When would I use package-private in Java?

NobleUplift picture NobleUplift · Aug 22, 2013 · Viewed 18.1k times · Source

I love access control in any language, but I find that in Java I almost never (if ever) use the package-private access modifier (or lack thereof).

I realize that inner classes can be private, protected, or package-private, but outer classes can only be package-private or public. Why can an outer class be package-private but not protected? What is the benefit of restricting classes/methods/fields to be seen by the entire package, but not subclasses?

Answer

dkatzel picture dkatzel · Aug 22, 2013

I use package-private classes and methods when I want to hide implementation details from users (and other classes) outside the package.

For example if I have an interface and a factory class that creates instances of that interface, I may have the implementation class as a separate file but mark it package-private so others can not use it, nor will it clutter the JavaDoc (if javadoc set to only show public).

If you seal your jar file, package-private methods can also help restrict who can access these methods. If a method is public or protected, subclasses can still see and call that method even if it's in a different package. (Unsealed jars allow anyone to make classes in your packages so they will get access to package-private or protected methods)