Sometimes you may want to prevent a subclass from overriding a method in your class. To do this, simply add the keyword final at the start of the method declaration in a superclass. Any attempt to override a final method will result in a compiler error.
class base
{
final void display()
{
System.out.println("Base method called");
}
}
class Derived extends Base
{
void display() //cannot override
{
System.out.println("Base method called");
}
}
class finalMethod
{
public static void main(String[] args)
{
Derived d =new Derived();
d.display();
}
}
On compiling the above example, it will display an error
The following points should be remembered while using final methods.
• Private methods of the superclass are automatically considered to be final. This is because you cannot override a method in the subclass. Similarly, the static methods are also implicitly final as they cannot be overridden either.
• Since the compiler knows that final methods cannot be overridden by a subclass, so these methods can sometimes provide performance enhancement by removing calls to final methods and replacing them with the expanded code of their declarations at each method call location. This technique of replacing code is known as inlining the code. There is no transfer of control between the calling and the called method that result in removing the method call overhead which in turn improves the execution time.
Methods made inline should be small and contain only few lines of code. If it grows in size, the execution time benefits become a very costly affair.
• A final’s method declaration can never change, so all subclasses use the same method implementation and call to one can be resolved at compile time. This is known as static binding.