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

血红的双手。 提交于 2019-11-30 20:41:35

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)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!