Java 最终类中受保护方法的用例是什么?
考虑官方 java.awt.font.TextLayout 的 ="noreferrer">OpenJDK 源:
public final class TextLayout {
/* ... */
protected void handleJustify(float justificationWidth) {
// never called
}
}
这里的用例是什么以及为什么会这样一般来说,编写这样的代码有意义吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
protected
成员仍然可以通过同一包中的代码访问。我的猜测是,该类在某些早期(可能甚至不是公共)版本中曾经是非最终的,然后被定为最终的,并且受保护的方法保持原样,因为在同一个包中可能有使用它的代码(而不是更改为私有包只是因为没有人看到这样做的好处)。protected
members can still be accessed by code from the same package. My guess is that the class used to be non-final in some earlier (perhaps not even public) version, was then made final, and the protected method kept as such because there might be code in the same package that uses it (and not changed to package private simply because nobody saw a benefit from doing so).受保护的是(请参阅访问级别):
对于
final
类,该方法由同一包中的其他类使用:它与没有访问修饰符(也称为“包私有”)相同。Protected is (see access levels):
In the case of a
final
class, the method's used by other classes in the same package: it's the same as no access modifier (also called "package-private").仅在其自己的包中使用
protected - 成员 - 仅在其包及其子类中可访问,
如果有人将方法定义为最终方法,则该方法不能被覆盖和动态查找。
参考这里:http://www.javacamp.org/javaI/Modifier.html
To be used only in its own package
protected - member - Accessible only within its package and its subclasses
if someone defines a method as final then it cannot be Cannot be overridden and dynamically looked up.
Reference here: http://www.javacamp.org/javaI/Modifier.html
该类无法进一步扩展或子类化,但仍然可以从包内访问该方法。
The class cannot be further extended or subclassed, but the method is still accessible from within the package.
事实就是这样:如果这是一个扩展了另一个类的类,则受保护的方法可能会扩展超类中的受保护的方法。另一个需要寻找的可能原因。
Just so it's out there: if this was a class that extended another, the protected method might be extending a protected method in the superclass. Another possible reason to look for.