From the Trenches of the Enterprise Software

Yakov Fain

Subscribe to Yakov Fain: eMailAlertsEmail Alerts
Get Yakov Fain via: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn

Related Topics: Java Developer Magazine, Open Source Journal, JavaScript

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:


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 Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain