Can We Extend Final Method in Java?

Java Final Methods

The final keyword in Java can be used to prohibit method overriding, declare constants, and stop inheritance. A method that is marked as final indicates that subclasses are not allowed to override it. It can be very helpful in a number of situations, including:

  1. Ensuring Security and Integrity: In certain situations, you may want to make sure that subclasses are unable to change a method's implementation and that it stays consistent. Applications that are security-sensitive frequently do this.
  2. Performance Optimisation: Since the Java compiler is aware that a final method would not be overridden, it can optimise it more effectively than a non-final method. In some cases, this can result in better performance.

Declaring a Final Method

A final method is declared using the final keyword before the method's return type. Here is an example:

In the above example, the displayMessage method is declared as final in the ParentClass. This means that any subclass of ParentClass will not be able to override this method.

Attempting to Override a Final Method

If we attempt to override a final method in a subclass, the Java compiler will generate an error. Here is an example to illustrate this:

Output:

Can We Extend Final Method in Java?

To provide a comprehensive understanding, let's look at a practical example involving a parent class with a final method and a subclass attempting to override it.

File Name: ChildClass.java

Output:

 
Details from the ParentClass.
Message from the ChildClass.   

In this example, the showDetails() method in the ParentClass is declared as final, preventing the ChildClass from overriding it. However, the showMessage() method is not final, allowing the ChildClass to provide its own implementation.

Conclusion

A final method in Java is one that subclasses are unable to override. It can help to preserve the integrity and security of the method's behaviour by guaranteeing that the implementation of the method stays unaltered. A compilation error will occur ifwe try to override a final method. Developers may construct their Java classes and methods more intelligently if they comprehend the purpose of final methods.