In this tutorial we will learn the usage of final keyword. final keyword can be used along with variables, methods and classes. We will cover following topics in detail.
1) final variable
2) final method
3) final class
1. Final Variables
final variables are nothing but constants. We cannot change the value of a final variable once it is initialized. Lets have a look at the below code:
class Demo{ final int MAX_VALUE=99; void myMethod(){ MAX_VALUE=101; } public static void main(String args[]){ Demo obj=new Demo(); obj.myMethod(); } }
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The final field Demo.MAX_VALUE cannot be assigned at beginnersbook.com.Demo.myMethod(Details.java:6) at beginnersbook.com.Demo.main(Details.java:10)
2. Final Methods
A final method cannot be overridden. Which means even though a sub class can call the final method of parent class without any issues but it cannot override it.
final modifier indicates that the method may not be overridden in a derived class.
3. Final Class
We cannot extend a final class.
When applied to a class, the final modifier indicates that the class can not be used as a base class to derive any class from it.