What is final keyword
final
is a reserved word or a keyword in java. It can be applied to
- A variable. This variable may be a method local variable or an instance variable. The instance(or class) variable may be static or non-static.
- A method, or
- A class.
Significance of final
keyword for all of the above will be explained in this article.
final keyword for variables
There are two kinds of variables: class(or instance) variables and local variables.
Local variables can be
1. Method arguments,
2. Variables declared inside a method,
3. Variables defined inside loops.final
keyword when applied to any of these variables means that the variable can be assigned a value only once. If you try to reassign a value to a variable, it results in a compiler error.
Local final variables
Variables defined inside a method, method arguments, variables inside a loop or as loop counters are local variables.
Below is an example of a final variable declared inside a method.
public class FinalVariableExample { public static void main(String[] args) { // declare and initialize a method local final variable final int count = 0; // re-initialize final variable count = 10; // compiler error } // final method argument void print(final String message) { System.out.print(message); } }
Above example declares and initializes a local final variable in a method and a final method argument. If an attempt is made to change their value, an error is raised “The final local variable i cannot be assigned.”
Following is an example of using final variable inside a loop.
public class FinalVariableExample { public static void main(String[] args) { for (int i = 0; i < args.length; i++) { // declare and initialize a loop local final variable final int count = i; } }
Above example declares a final variable inside a for loop.
Since, in every iteration, a new variable is created, thus it is allowed but if you try to change the value of final variable, a compiler error will be raised.
Variables used as loop counters can not be marked final
since they are incremented(and hence, reinitialized) after every iteration. Thus, following is illegal
for(final int counter = 0; counter < 10; counter++) { }
resulting in compile time error “The final local variable counter cannot be assigned”.
final class variables
A final instance(or class) variable can be
- declared and initialized in the same line or
- declared and initialized later.
Only thing to remember is that it can be initialized only once. Thus, below code statements are valid
public class FinalClassVariableExample { // final variable declared and initialized final int count = 0; // final variable declared final int later; void go() { // final variable initialized later = 10; } }
A class variable which is only declared but not initialized is called blank final variable.
It can only be initialized:
A. Inside the constructor of the class
Example,
public class BlankFinalVariableExample{ // blank final variable private double total; /* * Constructor */ public BlankFinalVariableExample() { total = 10.20; } }
If the class contains more than one constructor, then the final(or blank final) variable needs to be initialized in every constructor.
B. Inside initializer block
An initializer block is an unnamed block of curly braces which is executed whenever an object of a class is created. Example,
public class BlankFinalVariableExample{ // blank final variable private double total; /* * Initializer block */ { total = 10.20; } }
A class variable which is static
can only be
- initialized in the same line or
- inside a static block.
Trying to initialize it anywhere else will be a compiler error. Thus, below declarations are valid.
public class StaticVariableExample { // declare static final variable private static final int j; // static block static { // initialize static final variable j = 10; } // declare and initialize at the same time static final int k = 20; }
final keyword for method
final
keyword when applied to a method means that a sub-class(or child class) cannot override a method.
This is usually done when you want sub-classes to use the parent class implementation of a method and that they are not able to change it.
If a sub-class tries to override a method which is marked as final
, then the compiler will raise an error. Example,
public class Parent { // final method in parent public final void print() { System.out.print("Parent method"); } } public class Child extends Parent { // Overridden method: Will be a Compiler Error !!! public final void print() { System.out.print("Child method"); } }
Above example will result in a compiler error over the child class “Cannot override the final method from Parent”.
You also cannot apply @Override annotation over a method in child class that is marked final
in parent class
final keyword for class
final
keyword when applied to a class means that you cannot extend this class. In other words, if a class is marked final
, then its child class cannot be created.
A class is made final so that no one can extend and change its functionality.
Often, final
is also applied to make a class immutable. Example,
public final class FinalClassExample { } // Compiler Error !!! public class Child extends FinalClassExample { }
Above example will generate a compiler error “The type Child cannot subclass the final class FinalClassExample”.
This is because a class is trying to extend a final class.
Remember that trying to break the rules of final
keyword will always result in a compile time error. They will never lead to runtime exceptions.
final classes in java api
Following are final classes in java library
java.lang.String
java.lang.StringBuffer
java.lang.StringBuilder
- Wrapper classes such as
java.lang.Integer
,java.lang.Character
etc. java.lang.Math
Advantages of final keyword
Applying final
before classes, methods or variables have below benefits.
final
when written before a class prevents it from being sub-classed. Thus, you can be sure that the class is not modified by extending it and adding new methods to it.final
keyword before a method makes it safe from being overridden. This means that the desired behavior of a class is not modified by its child classes.- Adding
final
keyword before variables prevents their values from accidental modification thus, preventing unexpected behavior.
Hope this post clarified the use of final
keyword in java and where it can be applied.