Final Variable


Final Variable

The final keyword is a non-access modifier. In Java, “final” is used as a keyword while declaring a variable or any other entity so that their value can not be modified in the future during the compilation process.

The entities are:-

  • Variables
  • Parameters
  • Methods
  • Classes

Syntax for declaring final method:

public final void test()
{
//code body
}

Syntax for declaring final class:

public final class Test{
{
//code body
}

Final Keyword

If we declare a final keyword before a variable, then the assigned value can never be changed once after initialized.
If we do not initialize the final variable at the time of declaration, it is called a blank final variable.
For initializing the blank variable, we need to create a constructor. Only then the value can be initialized.

class A{
         final variable1 = 20;
             variable1 = 40; //Gives an error
}

We can modify the object:
A obj = new A();
obj.variable1 = 40 //Modification is allowed

Final Parameter

If a parameter defines as final, then its value will not change anywhere in the function.

class CheckParameter(final int x){
         x = 4; //attemps to change the variable will cause an error.
}

Final Method

By making any method final, the method can not be overridden by any other subclass. But we can inherit the final method; there is no restriction with the inheritance of the final method.

class A {
         final void FinalFunction(){
              System.out.print(“Hello”);
         }
}
Trying to override the FinalFunction() will cause an error.

Final Class

The final class not be extended.

final class A{}
class B extends A{ //error non extendable class
           public static void FaultFunction(){
        System.out.println(“Executed”);
   }
}

Example:

Com.knowledge2life public class Main { final String x = "Knowledge2life"; public static void main(String[] args) { Main myObj = new Main(); myObj.x = "Website"; System.out.println(myObj.x); } }

OUTPUT:

Main.java:6: error: cannot assign a value to final variable x
myObj.x = "Website";