
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can We Inherit a Final Method in Java
In Java, we cannot override a final method. Once a method is declared final, the Java compiler marks this method as non changeable. Therefore, behaviour of the final method will be the same throughout the application.
Suppose you are building an payment application. There is a method that calculates transaction fees based on the amount. You must declare this method as final to make sure each subclass use the same calculation logic.
What is a final Method in Java?
A method declared using the final keyword, is called as final method. The final keyword is a non-access modifier and used with variables, methods and classes to make them non-changeable.
Example
Below is an example of using a final method in Java:
class Parent { // a final method final void showMessage() { System.out.println("Inside a final method of Parent class"); } } public class Example { public static void main(String[] args) { Parent obj = new Parent(); // method call obj.showMessage(); } }
On running the above code, you will get the following result:
This is a final method from Parent.
Overriding a final Method in Java
If a subclass attempts to override a final method, the compiler will throw an error. The class which contains the final method can be inherited but, the subclass is not allowed to provide a new implementation of the method.
Example
Below is an example of trying to override a final method in sub class:
class Parent { // a final method final void showMessage() { System.out.println("Inside a final method of Parent class"); } } class Child extends Parent { // Trying to override final method void showMessage() { System.out.println("Overriding the final method"); } } public class Example { public static void main(String[] args) { Child obj = new Child(); // method call obj.showMessage(); } }
When you run the above code, you will get an error:
error: showMessage() in Child cannot override showMessage() in Parent overridden method is final
Conclusion
The final methods are used to make some important methods unchangeable, which prevents data from getting modified and maintains security of data.