Final Keyword in Java | Final Variable Method & Class - Scientech Easy

Final Keyword in Java | Final Variable Method & Class

In this tutorial, we will learn Final Keyword in Java. We will discuss three places where final can be used for field, methods, and classes. The final keyword declared with variable, method, and class indicates that "This cannot be modified". The value of the final variable cannot be changed. A final method cannot be overridden. A final class cannot be inherited. Let's see in detail.

Final Keyword in Java


Final is a keyword that is used to restrict the user in Java programming. Final Keyword in Java is a non-access modifier that is only applicable to a variable, a method, or a class. Java Final keyword has three different uses:
1. To create constants.
2. To prevent inheritance.
3. To prevent methods from being overridden.
Final class in Java, Java final method, Final variable in Java

Final Variable in Java


A variable declared with a final keyword is known as a final variable. Final variable means a constant (value cannot be modified). When the final variable once initialized, the value of the final variable can never be changed. In other words, we cannot be assigned a new value. The final variable must be declared at a time of declaration otherwise it will give a compilation error.
Syntax of Final variable in Java:
     Just add a final keyword in front of definition.
For example:
     final Float pi=3.14f;
Since the final variable means constant. Therefore, we cannot change the value of pi like.
      float pi=6.14f // compilation error.
A final keyword can be applied to local variables, instance variables, and static variables. In all cases, it does the same thing. Once you initialized the value of a final variable, you cannot assign a new value. 

Final Variable Example Program


In this example program, we are going to change the value of the final instance variable and final local variable but it can't be changed because the final variable once initialized a value can never be changed. Let's see the program source code.
Program source code 1: 
    package finalexample; public class FinalVariableEx { // Declare a final instance variable. final int a=20; // Declare an instance method. void change(){ // Change the value of the final instance variable. a=40; // compile time error. A final variable's value cannot be changed. System.out.println(a); // Declare a final local variable inside the method. final int i=0; for(i=0; i< 5; i++) // compile time error. { System.out.println("Value of I: " +i); } } public static void main(String[] args) { // Create an object of the class. FinalVariableEx fv=new FinalVariableEx(); // Call change() method using reference variable fv. fv.change(); } }
    Output: Exception in thread "main" java.lang.Error: Unresolved compilation problems: The final field FinalVariableEx.a cannot be assigned The final local variable i cannot be assigned. It must be blank and not using a compound assignment The final local variable i cannot be assigned. It must be blank and not using a compound assignment
We got a compilation error problem in the above program because we tried to change the value of final variables a and i.
A final variable that is created inside the constructor, method or block is known as a local final variable. It must be initialized once where it is created. See the above example program. We have declared a final local variable inside the method.

When to use a final variable


A final variable can be used where we want to remain constant the value of a variable throughout the execution of a program.
Note: The only difference between a normal variable and a final variable is that we can re-assign value to a normal variable but we cannot re-assign the value of a final variable once assigned.

Blank Final Variable


A variable that is declared as final and not initialized at a time of declaration is known as a blank final variable. A blank final variable must be initialized in the constructor of the class otherwise we will get a compilation error. Once the final variable is initialized in the constructor, it cannot be assigned a new value.
For example:
    class TestFinal { // Declaration of final instance variable. final int x; TestFinal(){ // Initialization of final variable in the constructor. x=20; } }  

Uninitialized Static Blank Final Variable


When a blank final variable is declared as static and not initialized at a time of declaration, it can only be initialized in the static block. It cannot be initialized in the constructor of the class. Remember this point. Let's see a simple example program.
Program source code 2:
    package finalexample; public class FinalVar { // Declare a blank final instance variable. final int x; // Declare a static blank final variable. final static int a; FinalVar(){ x=30; } void displayValue(){ System.out.println("Value of x: " +x); } // Declare a static block to initialize the final static variable. static { a=20; System.out.println("Value of a: " +a); } public static void main(String[] args) { // Create an object of the class. FinalVar fv=new FinalVar(); // Call change() method using reference variable fv. fv.displayValue(); } }
    Output: Value of a: 20 Value of x: 30

Reference Final Variable in Java


A final variable that is declared as a reference to an object is known as reference final variable. There is nothing like a final object in Java. If a final reference variable refers to an object then it does mean that the object is final. It simply means that the reference variable cannot refer to another object.
For example, a final List reference variable look like this
    final List list;
Here, the list is final. It does not mean that element cannot be added or removed from the list. The final list means the reference variable cannot refer to any new ArrayList. Any attempt to do so we will get compile time error.
Let's see a simple example program.
Program source code 3:
    package finalexample; import java.util.ArrayList; import java.util.List; public class FinalReferenceVarEx { public static void main(String[] args) { // Create an object of the list and declare as a final. final List<Integer> list=new ArrayList<Integer>(); // Adding elements in the list. list.add(20); list.add(30); list.add(40); System.out.println("Elements in the list"); System.out.println(list); list=new ArrayList<Integer>(); // Final local variable 'list' cannot refer to new ArrayList object. } }
    Output: Exception in thread "main" java.lang.Error: Unresolved compilation problem: The final local variable list cannot be assigned. It must be blank and not using a compound assignment

Can we change the state of an object to which a final reference is pointing?


Yes, we can change the state of an object to which a final reference variable is pointing but we cannot re-assign a new object to this final reference variable.

Final Method in Java


A method that is declared with the final keyword is known as final method. A final method cannot be overridden in Java. When a class is extended by another class, its method can be overridden for reuse but if we want to prevent a particular method being overridden, in this case, declare that method as final because a subclass can call the final method of superclass without any issues but it cannot override it. Any attempt to do so will cause the compilation problem.

Final Method Example Program


In this example program, we will call a final method of the parent class in the subclass without any issues and also try to override the final method in the subclass but it will give a compilation error. Let's see the program source code.
Program source code 4:
    package finalexample; public class FinalMethodEx { FinalMethodEx(){ System.out.println("This is a default constructor"); } final int a=50; final void show(){ System.out.println("Value of a: " +a); } } package finalexample; public class FinalMethodExTest extends FinalMethodEx{ void show(){ // Compile time error because we cannot override the final method from FinalMethodEx. System.out.println("This is the final method of FinalMethodEx class"); } public static void main(String[] args) { // Create an object of FinalMethodEx class. FinalMethodEx fm=new FinalMethodEx(); // Call final method using reference variable fm. fm.show(); } }
    Output: This is a default constructor Value of a: 50
Note:
1. A final method can be inherited in the subclass but we cannot override it. See the above example program.
2. The main difference between the abstract method and final method is that the abstract method must be overridden in the subclass but the final method cannot be overridden in the subclass.

Final Parameter in Java


If we declare any parameter as final, the value of the parameter cannot be changed after initialization.
Program source code 5:
    package finalexample; public class FinalParameterEx { final String nSchool; FinalParameterEx(){ nSchool="RSVM"; System.out.println("School name: " +nSchool); } void msg(final String name){ name="Lava"; // Compile time error because the final local variable cannot be changed. } public static void main(String[] args) { FinalParameterEx fp=new FinalParameterEx(); fp.msg("Shubh"); } }
    Output: School name: RSVM Exception in thread "main" java.lang.Error: Unresolved compilation problem: The final local variable name cannot be assigned.

Final Class in Java


A class that is declared with a final keyword is known as final class. Final class means Restricting inheritance!. A final class does not allow itself to be inherited by another class. In other words, Java classes declared as a final cannot be extended(inherited). If you do not want to be a subclass, declare it final. 
A lot of classes in the Java API are final. For example, String class is the most common predefined final class object in Java.

There are two ways to make a class as final.
1. The first way to make a class final is to use the final keyword in the class declaration.
     public final class Student {
           //------class contents
          } 
2. The second way is to declare all of its constructors as private. If a class has only private constructors, it cannot be subclassed. 
     public class Student {
            private Student(final int x) { 
                  }
          }
When you give private visibility for all constructors in the class, you are implicitly declaring the class as final.

Final Class Example Program


Let's see final class example program.
Program source code 6:
    package finalexample; public final class AB { void show(){ System.out.println("Final class cannot be inherited"); } } package finalexample; public class ABTest extends AB{ // Here compile-time error because the final class cannot be extended. public static void main(String[] args) { // Create the object of class AB. AB ab=new AB(); // Call show() method using object reference variable ab. ab.show(); } }
    Output: Compile time error
Program source code 7:
    package finalexample; public class AB { // Declare a default constructor as private to make a class as final. private AB(){ } void show(){ System.out.println("Final class cannot be inherited"); } } package finalexample; public class ABTest extends AB{ // Here compile time error because Implicit super constructor AB() is not visible for default constructor. Must define an explicit constructor. public static void main(String[] args) { // Create the object of class AB. AB ab=new AB(); // compile time error because the constructor AB() is not visible. // Call show() method using object reference variable ab. ab.show(); } }
    Output: Compile time error

What is the use of a final class in Java?


There are three uses a final class in Java.
1. The first use is to prevent the inheritance, as the final classes cannot be extended.
2. Second is to create an immutable class like the predefined String class. We cannot make a class immutable without making it final.
3. A final class is very useful when we want high security in any application because the final class cannot be extended.
            
Point to Remember:
1. A constructor cannot be final.
2. A block cannot be final.
3. A local final variable must be initialized at the time of declaration.
4. We cannot change the value of a final variable after initialization.
5. A final method cannot be overridden.
6. A final class cannot be extended(inherited).
7. We can create the object for a final class but cannot extend it.
8. If the method parameters are declared as final, the value of these parameters cannot be changed.   

Final words 
Hope that this article has covered almost all important topics related to Final keyword in Java. We hope that you have enjoyed reading about the final class, method, and variable in Java.
Thanks for reading!