Java Final keyword example
Final keyword in Java is a modifier used to restrict the user from doing unwanted code or preventing from the code or value from being changed. It is possible to use this keyword in 3 contexts. They are:
- Final keyword as a variable modifier
- Final keyword as a method modifier
- Final keyword as a class modifier
Each context has its own significance and restrictions implied. They are discussed in detail below.
1. FINAL keyword as a variable modifier
Each context has its own different purpose. final
, when used with a variable, it is specifically for restricting the user from changing the value anywhere else in the code. A final
variable, once initialized, its value cannot be changed.
If the final
variable is just declared but not initialized, it is allowed to assign a value to the final
variable once throughout the code. Any change in the value of final
variable more than once will result in compilation error.
For example, the below code will give a compile time error if tried to compile.
package com.mkyong;
public class FinalVariableExample {
final int count = 0;
public FinalVariableExample() {
count++; //The final field FinalVariableExample.count cannot be assigned
}
}
Output
Output: Compile Time error
2. FINAL keyword as a method modifier
final
, when used with method, it restricts the inheriting class from overriding the method definition. For example, the below example gives a compile time error because the FinalMethodChild
class tries to override the final
method testCode()
package com.mkyong;
public class FinalMethodParent {
final void testCode(){
System.out.println("This is a final method");
}
}
class FinalMethodChild extends FinalMethodParent{
//Cannot override the final method from FinalMethodParent
void testCode(){
System.out.println("This is overriding method");
}
}
Output
Output: Compile Time error
3. FINAL keyword as a class modifier
final
, when used for a class as a modifier, it restricts the class from being extended or inherited by any other class. For example, if you try to compile the below code, it gives a compile time error because the class FinalClassParent
is a final class which cannot be extended further.
package com.mkyong;
public final class FinalClassParent {
final void testCode(){
System.out.println("This is a final method");
}
}
//The type FinalClassChild cannot subclass the final class FinalClassParent
class FinalClassChild extends FinalClassParent{
void testCode(){
System.out.println("This is overriding method");
}
}
Output
Output: Compile Time error