Using the Final Keyword in Java

Contrary to popular opinion, the compiler cannot safely inline methods that have been declared as final. This is because these methods may have non-final declarations at runtime.

For example, suppose the compiler looks at class A, subclass B, and sub-subclass C. It sees a final method in A which it inlines into C. But at runtime, the versions loaded for A and B are different?the method is not final in A and it’s overridden in B. Finally, C uses the incorrectly inlined version. This is due to a bug in some early compilers with the -O option. Thus, tips suggesting using either final or the -O option are not valid.

Conversely, final methods can be inlined after you’ve loaded them into the JVM. Because at that point the JVM knows definitely that the method is final. Compilers that operate after class loading, such as JIT compilers, are able to take advantage of final methods. Consequently, methods declared as final may have some performance benefit.

Generally, don’t go out of your way to declare a method or class final purely for performance reasons. Only after you’ve definitely identified a performance problem is this even worth considering.

On the other hand, final variables, especially static final variables, are well worth using as standard.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: