简体   繁体   English

在Java的最终类中受保护方法的用例是什么?

[英]What's the use case of a protected method in a final class in Java?

Consider this code from the official OpenJDK source of java.awt.font.TextLayout : 请考虑来自java.awt.font.TextLayout的官方OpenJDK源代码

public final class TextLayout {

    /* ... */

    protected void handleJustify(float justificationWidth) {
      // never called
    }
}

What's the use case here and why might it make sense to write code like that in general? 这里的用例是什么?为什么编写这样的代码一般有意义?

Protected is (see access levels ): 受保护的是(参见访问级别 ):

  • For extending classes, regardless of package. 用于扩展类,不管包。
  • All classes in current package can access it. 当前包中的所有类都可以访问它。

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"). final类的情况下,该方法由同一个包中的其他类使用:它与无访问修饰符(也称为“package-private”)相同。

protected members can still be accessed by code from the same package. 仍然可以通过同一个包中的代码访问protected成员。 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的,然后是最终的,并且受保护的方法保持原样,因为在同一个包中可能存在使用它的代码(而不是改为私有包,因为没有人看到这样做的好处)。

To be used only in its own package 仅用于自己的包装

protected - member - Accessible only within its package and its subclasses protected - member - 仅在其包及其子类中可访问

if someone defines a method as final then it cannot be Cannot be overridden and dynamically looked up. 如果有人将方法定义为final,那么它就不能被覆盖并动态查找。

Reference here: http://www.javacamp.org/javaI/Modifier.html 参考这里: http//www.javacamp.org/javaI/Modifier.html

该类不能进一步扩展或子类化,但仍可从包中访问该方法。

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. 寻找的另一个可能的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM