Think twice before declaring a Java method as final

If you create classes that may be used by other developers, declaring methods as final will make them not overridable in the subclasses. While today, it may seem obvious to you that a particular method will never ever need to be overridden, you might not properly predict all use-patterns of this class. If this happens, some other developer will have to jump through the hoops to create another version of such a method in a subclass. If you don ‘t want to be cursed in the future, think twice if you really really want to declare this method as final. Do you see any benefits in using final methods?

We had to extend a third party library to improve their implementation of a certain networking protocol. As it usually happens, the code was poorly documented, so we had to read the code to find out which method to override in the subclass. Sure enough, that method was declared as final. We found a workaround and still replaced the call to the final method to the call to our own. So what the original developer achieved by using final? He made our work more difficult than it should have been.

Originally, Java compiler was optimizing (inlining) final methods. Today I ‘ve learned (thank you, Heinz) that Java compiler doesn ‘t do it anymore, and they are optimized by the Hotspot JVM:

http://www.javaspecialists.eu/archive/Issue157.html

http://www.javaspecialists.eu/archive/Issue158.html

Who are these guys we ‘re protecting from by using final? I also believe that the keyword protected is equally useless.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s