Witscale Test Center

3.5 Method declaration and modifiers > 3.5.3 Final methods


3.5.3 Final methods

A method can be declared final to prevent subclasses from overriding it. Thus, the behavior it implements becomes unchangeable.

Purpose

We have earlier seen some reasons why a class is defined as final namely the security concerns and design efficiency. However, sometimes declaring the whole class as final may not be feasible because a final class implicitly makes all its methods final.  If you have only few methods that are critical to the security, then declaring only them as final methods instead of making the whole class final is a better alternative. 

Since final methods cannot be overridden by the subclasses, there is no way you can change their implementation. If the methods that are critical to security are made final, system security and consistency is ensured. Final methods are expanded inline by the compiler, thus improving their speed of execution.

Declaration facts for final method

         You cannot declare a final method as abstract. Earlier we saw how the abstract method must be implemented in subclasses. But final methods can never be overridden (in subclasses) making it impossible to implement them in the subclass. Therefore, an abstract method can never be final or a final method can never be abstract.

         All methods declared in a final class are implicitly final, because it is impossible to override them. You need not redundantly include the final modifier while declaring such methods.