What's the use case of a protected method in a

2019-02-22 08:56发布

Consider this code from the official OpenJDK source of java.awt.font.TextLayout:

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?

5条回答
相关推荐>>
2楼-- · 2019-02-22 09:06

The class cannot be further extended or subclassed, but the method is still accessible from within the package.

查看更多
forever°为你锁心
3楼-- · 2019-02-22 09:08

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).

查看更多
▲ chillily
4楼-- · 2019-02-22 09:13

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").

查看更多
来,给爷笑一个
5楼-- · 2019-02-22 09:15

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.

查看更多
虎瘦雄心在
6楼-- · 2019-02-22 09:23

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

查看更多
登录 后发表回答