Java 'final' Keyword: Usage and Examples

Rumman Ansari   Software Engineer   2024-07-04 03:46:44   8024  Share
Subject Syllabus DetailsSubject Details 7 Program
☰ TContent
☰Fullscreen

Table of Content:

The final keyword in java is used to restrict the user. It is used to make a variable as a constant, Restrict method overriding, Restrict inheritance. It is used at variable level, method level and class level. In java language final keyword can be used in following way.

  1. Final at variable level
  2. Final at method level
  3. Final at class level

The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only.

final variable

  • A variable declared with the final keyword is known as a final variable.
  • It may be member variable or local variable.
  • If you make any variable as final, you cannot change the value of a final variable(It will be constant).
  • Final keyword is used to make a variable as a constant.This is similar to const in other languages.
  • A variable declared with the final keyword cannot be modified by the program after initialization.
Example: This is useful to universal constants, such as PI

Examples of final variable

Program:

public class Circle
{
	public  static final double PI=3.14159;

	public static void main(String[] args)
	{
		System.out.println(PI);
	}
}

Output:

3.14159
Press any key to continue . . .

Examples of final variable

Program:

final variables are constants in java and they are generally declared with static keyword. As final variables are treated as constants they can’t reassign. They are initialised at the time of declaration.

/**
 * This program is used to show that the value of
 * final variable can't be change.
 * @author atnyla developer
 */
class Test{
	//final variable
	final int num = 150;

	//method for try to change the value of final variable.
	public void show(){
		//error because value of final variable can't be change.
		num = 250;
		System.out.println("Num = " + num);
	}
}
public class FinalExample {
	public static void main(String args[]){
		//creating object of Test Class
		Test obj = new Test();
		//method call
		obj.show();
	}
}

Output:

C:\Users\FinalExample.java:13: error: cannot assign a value to final variable num
		num = 250;
		^
1 error

Tool completed with exit code 1


  

Examples of final variable

Program:

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed.

class Car{  
 final int speedlimit=90;//final variable  
 void run(){  
  speedlimit=400;  
 }  
 public static void main(String args[]){  
 Car obj=new  Car();  
 obj.run();  
 }  
}//end of class  

Output:

Compile Time Error

C:\Users\Car.java:4: error: cannot assign a value to final variable speedlimit
  speedlimit=400;  
  ^
1 error

Tool completed with exit code 1
  

Is it possible final method inherited?

Yes, final method is inherited but you cannot override it. For Example:

Program:

class Car{
  final void run(){
	  System.out.println("Car running...");
	  }
}
class Bike extends Car{
   public static void main(String args[]){
    new Bike().run();
   }
} 

Output:

Car running...
Press any key to continue . . .
  

Blank final variable

A final variable that is not initialized at the time of declaration is known as the blank final variable. We must initialize the blank final variable in the constructor of the class otherwise it will throw a compilation error (Error: variable MAX_VALUE might not have been initialized).


This is how a blank final variable is used in a class:

Program:

 class BlankV{
   //Blank final variable
   final int MAX_VALUE;

   BlankV(){
      //It must be initialized in constructor
      MAX_VALUE=500;
   }
   void myMethod(){
      System.out.println(MAX_VALUE);
   }
   public static void main(String args[]){
      BlankV obj=new BlankV();
      obj.myMethod();
   }
}
 

Output:

 500
Press any key to continue . . .
 

Program:

class Car{
  final int speedlimit;//blank final variable

  Car(){
  speedlimit=80;
  System.out.println(speedlimit);
  }

  public static void main(String args[]){
    new Car();
 }
}
 

Output:

80
Press any key to continue . . .
 

What's the use of blank final variable?

Let's say we have a Student class which is having a field called ROLL_NO. Since ROLL_NO  should not be changed once the student is registered, we can declare it as a final variable in a class but we cannot initialize ROLL_NO in advance for all the students(otherwise all students would be having the same ROLL_NO ). In such case, we can declare roll no variable as blank final and we initialize this value during object creation like this:

Program:

class StudentData{
   //Blank final variable
   final int ROLL_NO;

   StudentData(int rnum){
      //It must be initialized in constructor
      ROLL_NO=rnum;
   }
   void myMethod(){
      System.out.println("Roll no is:"+ROLL_NO);
   }
   public static void main(String args[]){
      StudentData obj=new  StudentData(21);
      obj.myMethod();
   }
}
 

Output:

Roll no is:21
Press any key to continue . . .
 

Uninitialized static final variable

A static final variable that is not initialized during declaration can only be initialized in static block Example:

Program:

class StaticFV{
   //static blank final variable
   static final int ROLL_NO;
   static{
      ROLL_NO=21;
   }
   public static void main(String args[]){
      System.out.println(StaticFV.ROLL_NO);
   }
}
 

Output:

21
Press any key to continue . . .
 

final method

  • When a method is declared with final keyword, it is called a final method.
  • A final method cannot be overridden. Which means even though a sub class can call the final method of parent class without any issues but it cannot override it.
  • The compiler checks and gives an error if you try to override the method.
  • When we want to restrict overriding, then make a method as a final.

Program:

class ClassP{
   final void demo(){
      System.out.println("ClassP Class Method");
   }
}

class ClassC extends ClassP{
   void demo(){
      System.out.println("ClassC Class Method");
   }

   public static void main(String args[]){
      ClassC obj= new ClassC();
      obj.demo();
   }
}
 

Output:

C:\Users\ClassC.java:8: error: demo() in ClassC cannot override demo() in ClassP
   void demo(){
        ^
  overridden method is final
1 error

Tool completed with exit code 1 
 

The above program would throw a compilation error, however we can use the parent class final method in sub class without any issues. Lets have a look at this code: This program would run fine as we are not overriding the final method. That shows that final methods are inherited but they are not eligible for overriding.

Program:

class ClassP{
   final void demo(){
      System.out.println("ClassP Class Method");
   }
}

class ClassC extends ClassP{
   public static void main(String args[]){
      ClassC obj= new ClassC();
      obj.demo();
   }
}
 

Output:

ClassP Class Method
Press any key to continue . . .
 

Example of final keyword at method level

Program:

class Employee
{
	final void display()
	{
	System.out.println("Hello Good Morning");
	}
}

class Developer extends Employee
{
	void display()
	{
	System.out.println("How are you ?");
	}
}

class MainClass
{
	public static void main(String args[])
	{
	Developer obj=new Developer();
	obj.display();
	}
}
 

Output:

C:\Users\Hello World\Documents\MainClass.java:11: error: display() in Developer cannot override display() in Employee
	void display()
	     ^
  overridden method is final
1 error

Tool completed with exit code 1

 

final class

  • When a class is declared with the final keyword, it is called a final class.
  • It makes a class final, meaning that the class can not be inherited by other classes.
  • We cannot extend a final class.
  • When we want to restrict inheritance then make the lass as a final.

Program:

final class ClassP{
}

class ClassC extends ClassP{
   void demo(){
      System.out.println("My Method");
   }
   public static void main(String args[]){
      ClassC obj= new ClassC();
      obj.demo();
   }
}
 

Output:

C:\Users\Hello World\Documents\ClassC.java:4: error: cannot inherit from final ClassP
class ClassC extends ClassP{
                     ^
1 error

Tool completed with exit code 1 
 

final parameter

If you declare any parameter as final, you cannot change the value of it.

Program:

 class CarFp{
  int cube(final int n){
   n=n+2;//can't be changed as n is final
   n*n*n;
  }
  public static void main(String args[]){
    CarFp b=new CarFp();
    b.cube(5);
 }
}
 

Output:

C:\Users\Hello World\Documents\Car.java:4: error: not a statement
   n*n*n;
      ^
1 error

Tool completed with exit code 1

 

Points to Remember:

1) A constructor cannot be declared as final.
2) Local final variable must be initializing during declaration.
3) All variables declared in an interface are by default final.
4) We cannot change the value of a final variable.
5) A final method cannot be overridden.
6) A final class not be inherited.
7) If method parameters are declared final then the value of these parameters cannot be changed.
8) It is a good practice to name final variable in all CAPS.
9) final, finally and finalize are three different terms. finally is used in exception handling and finalize is a method that is called by JVM during garbage collection.