Declaring a Construct as Final Simplifies Optimizations

In Java, the keyword final qualifies a construct (class, variable, or method) that may not be changed or overridden. Qualifying a variable as final ensures that the variable may not be assigned another value. Qualifying a class as final ensures that it is a leaf class?for example, it cannot be subclassed. Qualifying a method as final ensures that the method cannot be overridden by derived classes.

By declaring entities as final, you do the compiler a favor. In turn, you will be rewarded by efficiency in the executable code. Declaring a construct as final simplifies optimizations for the compiler. If a method is not declared as final, the runtime system has to determine the actual class of the object while the program is running, which severely hampers any optimizations the compiler can make when it compiles the code. If the method is declared final, it can be inlined (an invocation can be replaced within the actual body of the method during compilation) by the compiler.

Several compilers take this into account and the runtime system does its own optimizations. However, if you are trying to produce platform independent and VM independent code, you should try to recognize the non-extensible methods in your design and declare them final.

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


Recent Articles: