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

僤鯓⒐⒋嵵緔 提交于 2019-12-30 06:36:07

问题


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?


回答1:


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)




回答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.



来源:https://stackoverflow.com/questions/18382934/when-would-i-use-package-private-in-java

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