Welcome!

Java Authors: Tad Anderson, Yakov Fain, Pat Romanski, Colin Walker, Hovhannes Avoyan

Related Topics: Java

Java: Blog Feed Post

Think Twice Before Declaring a Java Method as Final

Declaring Methods as Final Makes Them Not Overridable By Other Developers

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.

More Stories By Yakov Fain

Yakov Fain is a Managing Director of Farata Systems, consulting, training and product company. He has authored several Java books, dozens of technical articles. SYS-CON Books released his latest co-authored book , Rich Internet Applications with Adobe Flex and Java: Secrets of the Masters in Spring 2007. Sun Microsystems has nominated and awarded Yakov with the title Java Champion. He leads the Princeton Java Users Group. He is an Adobe Certified Flex Instructor. Yakov co-athored the O'Reilly book "Enterprise Application Development with Flex". He twits at twitter.com/yfain.