我什么时候在Java中使用package-private? [英] When would I use package-private in Java?

查看:928
本文介绍了我什么时候在Java中使用package-private?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢任何语言的访问控制,但我发现在Java中我几乎从不(如果有的话)使用 package-private 访问修饰符(或缺少)。



我意识到内部类可以 private protected package-private ,但外部类只能是 package-private public 。为什么外部类可以 package-private 但不能 protected ?限制整个包所见的类/方法/字段有什么好处,而不是子类?

解决方案

我用 package-private 当我想要隐藏包外的用户(和其他类)的实现细节时的类和方法。



<例如,如果我有一个接口和一个工厂类来创建该接口的实例,我可能将实现类作为一个单独的文件,但将其标记为package-private,以便其他人不能使用它,也不会使JavaDoc混乱(如果javadoc设置为仅显示公共)。



如果密封jar文件,package-private方法也可以帮助限制谁可以访问这些方法。如果方法是公共的或受保护的,则子类仍然可以查看并调用该方法,即使它位于不同的包中。 (未密封的jar允许任何人在你的包中创建类,以便他们可以访问包私有或受保护的方法)


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?

解决方案

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)

这篇关于我什么时候在Java中使用package-private?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆