Final Keyword in Java – Learn to Implement with Methods & Classes

Free Java courses with 37 real-time projects - Learn Java

The final keyword in java is one of the most useful keywords when it comes to implementing security to a program. It restricts the user from changing the values or contents declared as final. The final keyword can be used with variables, methods and classes. In this article, we will take a look at the implementation of the final keyword in a java program.

What is the Final Keyword in Java?

As the word-final suggests, we can finalize a certain entity using the final keyword. In other words, anything declared final in the java program cannot be modified. The final keyword restricts the access of the user to modify the data.

  • A variable that is declared as a final variable is a constant throughout the program and its value cannot be changed whatsoever.
  • Method that is declared final cannot be overridden by any other subclasses.
  • A class that is declared final cannot be inherited by any other class.

Final Variable in java:

Final variables are constants that cannot be altered throughout the program. After the initialization of the final variable, it is finalized and alteration is not possible. If we try to alter it, we will get a compilation error.

The syntax for Defining Final Variable in java:

final <datatype> <variable name>=<value>;//final variable
final <datatype><variable name>;//blank final variable
static final <datatype><variable name>=<value>;//final static variable

Code to understand the implementation of the final Variable:

package com.DataFlair.Final;
public class Intern
{
   final int SALARY=10000;
   void change(){  
      SALARY=10500;
   }  
   public static void main(String args[]){  
      Intern i=new Intern();  
      i.change();  
   } 
}

The output of the above code:

Compile Time Error

The above code will give a compile-time error as we are trying to reassign the value of a final variable. It is impossible to do so, and hence the program won’t compile.

Blank final variable in Java:

We can declare a final variable and not initialize it, this type of final variable is known as a blank final variable. We have to initialize the variable in a constructor, otherwise, it will give a compilation error that the variable might not have been initialized.

Code to understand the implementation of the blank final Variable:

package com.DataFlair.Final;
public class Intern
{
   final int SALARY;
   Intern()
   {
       SALARY=10000;
   }
   void show(){  
      System.out.println(SALARY);
   }  
   public static void main(String args[]){  
      Intern i=new Intern();  
      i.show();  
   } 
}

The output of the above code:

10000

What is the use of a blank final variable?

We might have a final variable that has a different value for different cases, in this case, if we initialize the variable at first, it will have the same value for all cases. For example, in a company, every employee has an employee id, it is a final variable that cannot be changed. So, if we declare and initialize it at the same time, all the employees will have the same employee id. In such cases, the employee id is declared while object creation.

Code to understand the use of blank final variables:

package com.DataFlair.Final;
public class Employee
{
   final int EMPLOYEE_ID; 
   Employee(int eid){
      EMPLOYEE_ID=eid;
   }
   void show(){  
      System.out.println("The Employee ID is:"+EMPLOYEE_ID);
   }  
   public static void main(String args[]){  
      Employee e1=new  Employee(112131221);  
      e1.show();  
   }
}

The output of the above code:

The Employee ID is:112131221

Uninitialized static final variable in Java:

We can declare a static final variable and not initialize it right away. But this variable can only be initialized in a static block inside the code.

Code to understand the implementation of uninitialized static final variable:

package com.DataFlair.Final;
public class Employee
{
   static final int EMPLOYEE_ID; 
   static
   {
       EMPLOYEE_ID=112131221;
   }
   void show(){  
      System.out.println("The Employee ID is:"+EMPLOYEE_ID);
   }  
   public static void main(String args[]){  
      Employee e1=new  Employee();  
      e1.show();  
   }
}

The output of the above code:

The Employee ID is:112131221

Reference Final Variable in Java:

We can use a final variable as a reference to an object, this is known as the reference final variable. For Example final StringBuffer S;
We can change the internal state of the object that the final variable is pointing to. This doesn’t mean that the property of the final variable is violated, we are not reassigning the value but changing the state of the object.

Code to Understand Reference Final Variable:

package com.DataFlair.Final;
public class FinalReference
{
    public static void main(String[] args) 
    {
        final StringBuilder S = new StringBuilder("Data");
        System.out.println(S);
        S.append("Flair");  
        System.out.println(S);
    }    
}

The output of the above code:

Data
DataFlair

Java final method:

A final method is a method that cannot be overridden. We can call a final method from a subclass, but the subclass cannot override the final method of the parent class. If we try to do so, it will give a compilation error.

Code to understand what will happen if we try to override a final method:

package com.DataFlair.Final;
public class Company
{
     final void comment(){
      System.out.println("Only Company admin can access");
   }  
}  
public class Intern1 extends Company
{
    void comment()//Trying to override
   {
      System.out.println("Intern trying to access admin!!!!");
   } 
   public static void main(String args[]){  
      Intern1 i1= new Intern1();  
      i1.comment();  
   } 
}

The output of the above code:

Compile Time Error

The above code didn’t run as the extended class tried to override the final method which is illegal. Let us write the code now in such a way that it runs without error.

Code to implement final method properly:

package com.DataFlair.Final;
public class Company
{
     final void comment(){
      System.out.println("Only Company admin can access");
   }  
}  
public class Intern1 extends Company
{
   public static void main(String args[]){  
      Intern1 i1= new Intern1();  
      i1.comment();  
   } 
}

The output of the above code:

Only Company admin can access

This code did run, as the extended class only called the final method and did not try to override the final method.

Purpose of Java Final Method:

The java final method increases security. A final method prevents the subclass from overriding the definition of a method. If there is a method that contains a definition that should not be altered by the extended classes, it should be declared final to prevent overriding, this increases security while implementing the program.

Java final class:

When there is a class that is a stand-alone and should not be inherited in any circumstances, it should be declared final. A final class cannot be inherited whatsoever.

Code to understand what happens when we try to inherit a final class:

package com.DataFlair.Final;
final public class Company
{
      void comment(){
      System.out.println("Only Company admin can access this class!");
   }  
}  
public class Intern1 extends Company
{
   public static void main(String args[]){  
      Intern1 i1= new Intern1();  
      i1.comment();  
   } 
}

The output of the above code:

Compile Time Error

Java final parameter:

We can declare a parameter final, but then we will not be able to change the value of the parameter inside the method.

Code to understand what happens when we try to change the value of a final parameter:

package com.DataFlair.Final;
public class FinalParameter
{
   int square(final int n)
   {  
   n=n+2;//can't be changed as n is final  
   return n*n;  
  }  
  public static void main(String args[]){  
    FinalParameter p=new FinalParameter();  
    p.square(10);  
 }  
}

The output of the above code:

Compile Time Error

The above code did not run because we tried to change the value of a final parameter.

Code to implement final parameter properly:

package com.DataFlair.Final;
public class FinalParameter
{
   int square(final int n)
   { 
   return n*n;  
  }  
  public static void main(String args[]){  
    FinalParameter p=new FinalParameter();  
    int sq=p.square(10);  
    System.out.println(sq);
 }  
}

The output of the above code:

100

Important points to Remember:

1. We cannot declare a constructor as final.

2. Local final variables cannot be kept uninitialized.

3. The default datatype of all variables in an interface is final.

4. The value of a final variable is unaltered throughout.

5. Overriding a final method is impossible.

6. Inheriting a final class is impossible.

7. A final parameter has a value that cannot be altered inside the method.

8. final, finally and finalize should not be confused as the same. They are very different concepts. finally is used in exception handling whereas finalize is used in garbage collection.

Conclusion:

In this article, we saw the use of a final keyword, as when and where we can use them. A final keyword is very important when it comes to security as thus knowing its proper implementation is a key concept.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

follow dataflair on YouTube

2 Responses

  1. Rahul diwan says:

    How can i access final class in java

Leave a Reply

Your email address will not be published. Required fields are marked *