我什么时候会在 Java 中使用 package-private? [英] When would I use package-private in Java?
问题描述
我喜欢任何语言的访问控制,但我发现在 Java 中我几乎从不(如果有的话)使用 package-private 访问修饰符(或缺少).
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).
我意识到内部类可以是 private
、protected
或 package-private
,但外部类只能是 package-private
或 public
.为什么外部类可以是 package-private
而不是 protected
?限制类/方法/字段被整个包看到,而不是子类看到有什么好处?
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?
推荐答案
当我想对包外的用户(和其他类)隐藏实现细节时,我使用 package-private
类和方法.
I use package-private
classes and methods when I want to hide implementation details from users (and other classes) outside the package.
例如,如果我有一个接口和一个创建该接口实例的工厂类,我可能将实现类作为一个单独的文件,但将其标记为包私有的,这样其他人就不能使用它,也不会弄乱 JavaDoc(如果 javadoc 设置为只显示 public).
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).
如果你密封你的 jar 文件,包私有方法也可以帮助限制谁可以访问这些方法.如果一个方法是公共的或受保护的,即使它在不同的包中,子类仍然可以看到和调用该方法.(未密封的 jar 允许任何人在您的包中创建类,以便他们可以访问包私有或受保护的方法)
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屋!