Final Keyword in Java

Final Keyword in Java

In this article, I am going to discuss the Final Keyword in Java with Examples. Please read our previous where we discussed Garbage Collection in Java in detail. At the end of this article, you will understand the following pointers in detail.

  1. What is Java Final Keyword?
  2. Final Variables in Java
  3. How to initialize a blank final variable?
  4. When to use Final Variable in Java?
  5. What is the Reference Final variable?
  6. Final Methods in Java
  7. Final Class in Java
What is Java Final Keyword?

In the Java programming language, the final keyword is used in several contexts to define an entity that can only be assigned once. The final keyword is used in different contexts. First of all, the final is a non-access modifier applicable only to a variable, a method, or a class. Following are the different context of using final keyword:

Final Keyword in Java

The final keyword in java is used to restrict the user. In Java, the final keyword can be used while declaring an entity. Using the final keyword means that the value can’t be modified in the future.

Final can be:

  • Variables
  • Methods
  • Classes
Final Variables in Java

When a variable is declared with the final keyword, its value can’t be modified, essentially, a constant. This also means that you must initialize a final variable. The final variable cannot be reinitialized with another value. However, the data within the object can be changed. So, the state of the object can be changed but not the reference. With variables, the final modifier often is used with static to make the constant a class variable.

Note :

  • The variable does not necessarily have to be initialized at the time of declaration. If it’s declared but not yet initialized, it’s called a blank final variable. This approach is the most common.
  • It is recommended to use uppercase to declare final variables in Java.
How to initialize a blank final variable?

Below are the two ways to initialize a blank final variable:

  1. A blank final variable can be initialized inside the instance-initializer block or inside the constructor. If you have more than one constructor in your class then it must be initialized in all of them, otherwise, a compile-time error will be thrown.
  2. A blank final static variable can be initialized inside a static block.
When to use Final Variable?

Final Variables must be used only for the values that we want to remain constant throughout the execution of the program because a final variable is that we can re-assign value to a normal variable but we cannot change the value of a final variable once assigned.

Sample Program to demonstrate the final variable in Java:
package Demo;

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

Output: Compile-Time Error

There is a final variable speed limit, we are going to change the value of this variable, but it can’t be changed because the final variable once assigned a value can never be changed.

What is the Reference Final variable?

The final reference allows you to modify the state of the object but you cannot modify the reference variable to point to a different object in the memory. For Example, final Person p1;

In the case of a reference final variable, the internal state of the object pointed by that reference variable can be changed. Note that this is not re-assigning. This property of the final is called non-transitivity.

Sample Program to demonstrate Reference Final Variable in Java:
package Demo;

public class Person {
 String name;
    	int age;
       
       public static void main(String[] args) {
              final Person p1 = new Person(); //Reference Final Variable
              p1.age = 12;
              p1.name = "John";
              //This is legal. You can modify the state of final reference.
             p1.age = 30;
             p1.name = "Peter";
       }
}
Final Methods in Java

A final method cannot be overridden or hidden by subclasses which means even though a subclass can call the final method of parent class without any issues but it cannot override it. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class. We must declare methods with the final keyword for which we required to follow the same implementation throughout all the derived classes. The main intention of making a method final would be that the content of the method should not be changed by any outsider.

Sample Program for demonstrating Final Methods in Java:
package Demo;

class Bike{  
   final void run(){System.out.println("running");}  
}  	     
class Honda extends Bike{  
      void run(){
    // COMPILE-ERROR! Can't override.
           System.out.println("running safely with 100kmph");
      }  
      public static void main(String args[]){  
    Honda honda= new Honda();  
    honda.run();  
      }  
}

Output: Compile-Time Error

In the above example, we have tried to override the final method in the main() class. When we run the program, we will get a compilation error.

Final Class in Java

In Java, the final class cannot be inherited by another class.  The main purpose of using a class being declared as final is to prevent the class from being subclasses. If a class is marked as final then no class can inherit any feature from the final class. When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. For scalar values, once it has been assigned, the value of the final variable cannot change. For object values, the reference cannot change.

Sample Program to demonstrate Final Class in Class:
package Demo;

final class FinalClass {
    // create a final method
    public void display() {
      System.out.println("This is a final method.");
    }
}

class Main extends FinalClass {
  // try to override final method
  public  void display() {
    System.out.println("The final method is overridden.");
  }

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

Output: Compile-time Error

In the above example, we have created a final class named Final class. Here, we have tried to inherit the final class by the Main class. When we run the program, we will get a compilation error 

Note :
  • The final method can be inherited but you cannot override it.
  • Blank Final Variable can be initialized only in the constructor.
  • Constructors cannot be declared as final because it cannot be inherited.

In the next article, I am going to discuss the Static Keyword in Java with Examples. Here, in this article, I try to explain the Final Keyword in Java with examples. I hope you enjoy this Final Keyword in Java with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this Final Keyword in Java with Examples article.

Leave a Reply

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