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

Final Keyword in Java is used to finalize the value of a variable, class or method in the entire program. It stores the initialized value in the memory which will never change at any condition. There are much more to learn and implement the final keywords. So, let’s start with the introduction to Final Keywords.

Stay updated with the latest technology trends while you're on the move - Join DataFlair's Telegram Channel

What is Java Final Keyword?

Final keyword in Java is used in many contexts like it can be used as a variable, it can be a class or can be a method. Inheritance enables us to reuse the existing code but sometimes we want to restrict the extensibility; the final keyword allows us to do so. It is a non-access modifier that means if you make a variable or class final then you are not allowed to change that variable or class and if you try then the compiler will throw compilation error.

Example-

final int number = 5;

Brush-up your skills with Access Modifiers in Java

Implementation of Final Keywords

Implementation of Final Keyword in Java

1. Java Final Variable

We should initialize a final variable in Java, otherwise, a compiler can throw a compile-time error. A Java final variable will only initialize once, either via an initializer or an assignment statement.

There are 3 ways to initialize a Java final variable:

  • You can initialize a final variable when it’s declared. This approach is the most common. A final variable is named blank final variable if it’s not initialized whereas declaration.
  • A blank final variable is initialized within instance-initializer block or within a constructor. If you have got one constructor in your class then it should initialize in all of them, otherwise, a compile-time error is thrown.
  • A blank final static variable is initialized within a static block.

1.1 When to use a Final Variable in Java?

The only difference between a normal variable and a final variable is that we will re-assign value to a normal variable. However, we cannot change the value of a final variable once assigned. Therefore, Java final variables must be used for the values that we would like to keep constant throughout the execution of a program.

Java Final Variable

Let us see above different ways of initializing a Java final variable through an example.

package com.dataflair.finalkeyword;

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

Output-

Compile Time Error

Once a variable is initialized as final we cannot redeclare it.

1.2 Reference Final Variable in Java

When a Java final variable may refer to an object, then the final variable known is as reference final variable.

Don’t forget to check StringBuffer in Java

For example, a final StringBuffer variable seems like-

Final StringBuffer stringBufferVariable;

Example-

package com.dataflair.finalkeyword;

public class FinalVariable 
{
  public static void main(String[] args)  
  { 

    final StringBuilder stringbufferVariable = new StringBuilder("Data"); 
    System.out.println(stringbufferVariable); 
    stringbufferVariable.append("Flair"); 
    System.out.println(stringbufferVariable); 
  }     
} 

Output-

Final-variable-in-java

2. Java Final Class

A class which is declared using the final keyword is a final class. A final class can’t be extended. There are many final classes available in Java one of them is Java String class. If we try to inherit from final class then it will generate a compile-time error.

For example, All wrapper class in java like, float, integer etc. are Java final Class and we cannot extend them.

Example

package com.dataflair.finalkeyword;
final class DemoClass
{  
} 

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

Output-

Compile Time Error  “The type FinalClass cannot subclass the final class DemoClass”

The other use of final with classes is to make an immutable class like the predefined String class. You cannot create a class immutable while not creating it finally.

It’s time to learn about Inner Classes in Java 

3. Java Final Method

When a method is declared in Java using the final keyword, then it’s called a final method. A final method can not be overridden.  We should declare strategies with a final keyword in Java, that we tend to needed to follow constant implementation throughout all the derived classes. The subsequent fragment illustrates final keyword with a method:

package com.dataflair.finalkeyword;

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

class FinalMethod extends FinalMethodClass{  
  void demo(){
    System.out.println("FinalMethod Method");
  }  

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

}

The following program will throw an error, therefore we can use the parent class final method in subclass without any issues. Let’s see how we can overcome this problem.

package com.dataflair.finalkeyword;

class FinalMethodClass{  
  final void demo(){
    System.out.println("FinalMethodClass Method");
  }  
}  
class FinalMethod extends FinalMethodClass{  


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

}

Output-Final-Method-in-Java

Summary

We can use Final keyword in Java to restrict the user. It initializes the value once and can’t be changed during the action/entire process. Now, you practice this keyword with variables, methods, and classes.

If you face any doubt, feel free to share with us our experts will definitely get back to you!

Let’s discuss the different types of Exceptions in Java and how to deal with them

1 Response

  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 *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.