When would I use package-private in Java? [duplicate]
Asked Answered
A

2

6

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?

Aloeswood answered 22/8, 2013 at 14:12 Comment(0)
E
13

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)

Erdda answered 22/8, 2013 at 14:19 Comment(0)
F
2

In many cases, peer classes in the same package have the same author, thus he knows about the inner way these classes work, or in other words he knows about the encapsulated logic of these classes. Thus he can make sure that package-private accesses between classes adhere to the encapsulated logic of the accessed class and that these accesses do not break anything.

These direct accesses are often useful for optimizations and for keeping the amount of source code smaller.

For the question part why outer classes may be package-private, but not protected, I have no answer.

Flask answered 22/8, 2013 at 14:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.