Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

like image 431
soc Avatar asked Jul 28 '11 12:07

soc


People also ask

What is the use of protected method in Java?

Definition and Usage The protected keyword is an access modifier used for attributes, methods and constructors, making them accessible in the same package and subclasses.

What is the use of protected methods?

Protecting a constructor prevents the users from creating the instance of the class, outside the package. During overriding, when a variable or method is protected, it can be overridden to other subclass using either a public or protected modifier only. Outer class and interface cannot be protected.

What is the use of protected class in a package?

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

Is protected method final in Java?

1) Private methods are final. 2) Protected members are accessible within a package and inherited classes outside the package. 3) Protected methods are final.


1 Answers

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

like image 72
Michael Borgwardt Avatar answered Nov 12 '22 18:11

Michael Borgwardt