Final Keyword in Java
There are around 46 keywords in Java. Each keyword has a special purpose that fulfils the need of the programmer. The final keyword in Java also plays an indispensable role. You can apply the final keyword with a variable, method, or even in a class. This article depicts the various ways to use the final keyword in java programming.
Purpose of Java Final keyword:
The Final keyword mainly restricts the user from performing specific actions. It makes them helpless to change the given value. In other words, it is a non-access specifier that restricts the value of a variable from being changed.
So, what happens to a method with a final keyword? The methods with a final keyword cannot be overridden by other subclasses. The keyword is final to a class that puts a full stop to its inheritance property. No other class can extend or inherit a final class.
Let’s look at all these in detail.
Final variable in Java
We add the keyword final to the variable whose value we need not want to change. However, not abiding by this rule will lead to compilation errors. Therefore, changing the value of the variable declared with the final keyword is impossible.
A final variable is usually a constant as it acts as one whose value cannot be modified.
This is applicable in the case where we have only normal variables. If it is a reference variable, we should keep in mind that there is a restriction. This restriction with the final reference variable states that there is no possibility for us to change “What the object is referring to”. In contrast, we can change the object itself, which is not considered re-assigning. It is a property of the final keyword known as non-transitivity.
A final variable should already be declared. It should contain a value before adding the final keyword to it. A final variable without declaration is a blank final variable. It is advised to declare the final variable to avoid compilation errors.
Syntax to define a final variable:
final int num = 5; //final variable final float val; //blank final variable static final double rate = 1.5; //final and static variable
Final variable initialisation in Java:
As initialising a final variable in java is essential, here are the ways to do it:
1. An easy and simple way to initialise a final variable is during its declaration. When a variable is not declared, it is a blank final variable.
2. A blank final variable can be initialised inside an instance-initialiser block or the class’s constructor. If there are multiple constructors in the class, we must initialise the final variable in every constructor to avoid errors.
3. The other way to initialise the final static variable is inside a static block.
Code to implement Java final variable:
package com.dataflair. final; public class Books{ final int bookcount = 200; void increasebookcount() { //Trying to change the value of the final variable will throw an error bookcount = 350; } public static void main(String args[]) { Books obj = new Books(); obj.increasebookcount(); } }
Output:
com.dataflair.finalkeyword.Vehicle.java:9: error: cannot assign a value to final variable bookcount
bookcount= 150;
^
1 error
Code to implement the blank final variable:
package com.dataflair.finalkeyword; public class StudentDetails { //Blank final variable final int regno; //parameterized constructor StudentDetails(int regNum) { //Blank final variable must be initialized in the constructor reg = regNum; } void getDetails() { System.out.println("Register number of the Student is: " + reg); } public static void main(String args[]) { StudentDetails stu = new StudentDetails(213); stu.getDetails(); } }
Output:
Register number of the Student is: 213
Code to implement the final reference variable:
package com.dataflair.finalkeyword; public class FinalRefVariable { public static void main(String[] args) { // declaring a final reference variable builder final StringBuilder word = new StringBuilder("Data"); System.out.println(word); // changing the internal state of object reference by final reference variable builder word.append("Flair"); System.out.println(word); } }
Output:
Data
DataFlair
When to use Java final variable?
The only difference between a normal and a final variable is that we cannot alter the latter’s value. A value, once assigned, is fixed for a final variable, whereas this does not imply a normal variable.
Therefore, it is clear that we must use a final variable only when we do not want a value to be constant throughout the execution of the program.
Final Method in Java:
In the same way we add the keyword final in front of a variable name, and we add it to the method name to make it a Final Method.
This restricts the method from being overridden into subclasses. The declaration of the Final Method makes it impossible to change its definition of it in its subclasses. Though a class extends it, no modifications are applicable in a Final Method.
Code to implement the final method:
package com.dataflair.finalkeyword; public class Parentclass { final void final_method() { //definition of the Final Method } } public class Childclass extends Parentclass { final void final_Method() // overriding the method from the parentclass { // another definition of the final method } }
This code will generate a compile-time error. Here, the Final Method of the Child class overrides the Final Method of the parent Class, which is impossible in the Java programming language.
Purpose of Java Final Methods:
The final method in Java prevents the improper usage of the method’s definition while overriding. It is not logically improper. The final method aims to prevent misinterpretation by the reader. Therefore, we should avoid the unwanted method definitions and declare them as final.
Suppose we create a class Animal and a non-final method eat() in it. Assume that another programmer creates a class Goat and includes and overrides the eat() method. This might lead to misunderstanding and printing the wrong food name for Goat as Meat or Dear, etc.
This is a small example of how the method can be wrongly used. In such situations, we use the final method as given in the code below:
Code to implement Final method:
package com.dataflair.finalkeyword; public class Animal { final void characteristics() { int limbs = 4; int ears = 2; int eyes = 2; int tail = 1; System.out.println("The Characteristics of an Animal are: "); System.out.println("Limbs: " + limbs); System.out.println("Eyes: " + eyes); System.out.println("Ears: " + ears); System.out.println("Tail: " + tail); } } public class Goat extends Animal { final void eat() { System.out.println(); System.out.println("\nOther Characteristics:"); System.out.println("Food: Grass"); } public static void main(String[] args) { Goat g = new Goat(); g.characteristics(); g.eat(); } }
Output:
The Characteristics of an Animal are :
Limbs: 4
Eyes: 2
Ears: 2
Tail: 1
Other Characteristics:
Food: Grass
Final Class in Java:
Declaring a class with the Final keyword is also possible. It is to restrict the other classes from inheriting or extending it.
In other words, other classes cannot extend a Java class that is declared final. Any attempts to do it will result in a compilation error.
Code to implement Final class in Java:
package com.dataflair.finalkeyword; public class Child extends Parent { void run() { System.out.println("Displaying the output"); } public static void main(String[] args { Child c = new Child(); c.run(); } } final class Parent{ //code inside class }
Output:
Compilation error.
Conclusion:
I hope you are clear about implementing the final keyword with a variable method and a class. The Final keyword acts accordingly to the place where it is used. You can try out these sample programs to clearly understand their work.