Java Final Keyword, Variable, Method and Class

We know that there are 48 reserved keywords in Java and the final keyword is one of them. It is a keyword that can be used with entities in Java to restrict their use. We can use it with class, methods, variables.

There are different uses of the Java final keyword for different entities. That is, the purpose of using the final keyword is different for class, variable, and method.

In this article, we will discuss the final keyword in Java and learn to implement and use it with different parameters.

What is the Final Keyword in Java?

Java final keyword is a non-access specifier that is used to restrict a class, variable, and method. If we initialize a variable with the final keyword, then we cannot modify its value.

If we declare a method as final, then it cannot be overridden by any subclasses. And, if we declare a class as final, we restrict the other classes to inherit or extend it.

In other words, the final classes can not be inherited by other classes.

This was a brief introduction to a final keyword in Java. Now we will discuss the implementation of the final keyword with a variable, method, and class in Java. We will discuss the following topics in detail:

1. final variable
2. final class
3. final method

Final Keyword in Java

Final Variable in Java

Once we declare a variable with the final keyword, we can’t change its value again. If we attempt to change the value of the final variable, then we will get a compilation error.

Generally, we can consider a final variable as a constant, as the final variable acts like a constant whose values cannot be changed.

This rule was for the normal variables, what if we declare the reference variables as final? The restriction with the final reference variable is that we cannot change “what the object is referring to” but we can modify the object itself.

We can’t just declare a variable as final without initializing it. That is, we have to give it an initial value while declaring a final variable. If we declare the final variable without initialization, then it is a blank final variable.

But it is mandatory to initialize a final variable either during declaration or after declaration. If we leave it uninitialized, then we will get a compilation error.

Syntax of defining a final variable:

final int number = 10;                             //final variable
final float value;                                       //blank final variable
static final double rate = 2.5;             //final and static variable

Initializing Final Variable in Java

As we know that a final variable cannot be left uninitialized, the following are the ways to initialize a final variable:

1. The most common approach is to initialize a final variable during its declaration. But if you don’t initialize it while declaring it, then we call it as a blank final variable.

The next two ways are the ways to initialize a blank final variable.

2. We can initialize a blank final variable inside an instance-initializer block or inside the constructor of the class. In case, there are many constructors in the class, then you need to initialize the final variable inside each constructor, else there will be an error.

3. We can initialize a blank final static variable inside a static block.

Code to understand Java final Variable:

package com.techvidvan.finalkeyword;
public class Vehicle {
  //declaring and initializing a final variable
  final int speedlimit = 60;
  void controlSpeed() {
    //Trying to change the value of the final variable will give an error
    speedlimit = 150;
  }
  public static void main(String args[]) {
    Vehicle obj = new Vehicle();
    obj.controlSpeed();
  }
}

Output:

com.techvidvan.finalkeyword.Vehicle.java:9: error: cannot assign a value to final variable speedlimit
speedlimit = 150;
^
1 error

Code to understand the blank final variable:

package com.techvidvan.finalkeyword;
public class EmployeeDetails {
  //Blank final variable
  final int id;

  //parameterized constructor
  EmployeeDetails(int idNum) {
    //Blank final variable must be initialized in constructor
    id = idNum;
  }

  void getDetails() {
    System.out.println("Id of the Employee is: " + id);
  }

  public static void main(String args[]) {
    EmployeeDetails emp = new EmployeeDetails(154);
    emp.getDetails();
  }
}

Output:

Id of the Employee is: 154

Code to understand the final reference variable:

package com.techvidvan.finalkeyword;
public class FinalReferenceVariable {
  public static void main(String[] args) {
    // declaring a final reference variable builder
    final StringBuilder builder = new StringBuilder("Tech");

    System.out.println(builder);

    // changing internal state of object reference by final reference variable builder
    builder.append("Vidvan");

    System.out.println(builder);
  }
}

Output:

Tech
TechVidvan

When to use Java Final Variable?

The normal variable and final variable differ only by one parameter that we can change the value of a normal variable once assigned, but we cannot change the value of a final variable once assigned.

Therefore, we must use the final variables only for the assigning values that we want to remain constant throughout the execution of the program.

Final Method in Java

As earlier, we discussed the Final Keyword and How to declare the Final Variable. We can declare Java methods as Final Method by adding the Final keyword before the method name.

The Method with Final Keyword cannot be overridden in the subclasses. The purpose of the Final Method is to declare methods of how’s definition can not be changed by a child or subclass that extends it.

Code to understand the final method in Java:

package com.techvidvan.finalkeyword;
public class Parent {
  final void final_method() {
    //definition of the Final Method
  }
}
public class Child extends Parent {
  final void final_Method() // overriding the method from the parent class  
  {
    // another definition of the final method
  }
}

The above example of the Final Method generates a compile-time error.

As the Parent class Final method was overridden by the Child class Final method; that is not possible in the Java programming language.

Purpose of Java Final Methods

The purpose of creating the final methods is to restrict the unwanted and improper use of method definition while overriding the method.

Though it is not logically incorrect, it can change the meaning of the method and the reader might interpret it wrongly. Therefore, in such cases to prevent the unwanted method definitions, we declare methods as final.

Suppose we make a class Animal and declare a non-final method sound() in it. Someone creates a Dog class and overrides the sound() method in it and prints the wrong sound of the Dog such as Meow or Roar, etc.

This will make the wrong use of our method, so overcome this situation, we use the final method as shown in the below code:

Code to understand the purpose of the final Method:

package com.techvidvan.finalkeyword;
public class Animal {
  final void characteristics() {
    int legs = 4;
    int ears = 2;
    int eyes = 2;
    int tail = 1;
    System.out.println("General Characteristics of an Animal are: ");
    System.out.println("Legs: " + legs);
    System.out.println("Eyes: " + eyes);
    System.out.println("Ears: " + ears);
    System.out.println("Tail: " + tail);
  }
}
public class Dog extends Animal {
  final void sound() {
    System.out.println();
    System.out.println("Additional Characteristics:");
    System.out.println("Sound: Bhow Bhow");
  }
  public static void main(String[] args) {
    Dog d = new Dog();
    d.characteristics();
    d.sound();
  }
}

Output:

General Characteristics of an Animal are :
Legs: 4
Eyes: 2
Ears: 2
Tail: 1Additional Characteristics:
Sound: Bhow Bhow

Final Class in Java

We can also declare a class with a final keyword in Java. When we declare a class as final, then we restrict other classes to inherit or extend it.

In short, Java final class can’t be extended by other classes in the inheritance. If another class attempts to extend the final class, then there will be a compilation error.

Code Snippet for final class:

final class Tech {
  // methods and variables of the class Tech
}

class Vidvan extends Tech {
  // COMPILE- TIME error as it extends final class
}

Code to understand Final Class:

package com.techvidvan.finalkeyword;
public class Vidvan extends Tech {
  void test() {
    System.out.println("My Method");
  }
  public static void main(String[] args {
    Vidvan obj = new Vidvan();
    obj.test();
  }
}
final class Tech {
  //code inside class
}

Output:

Compile-time error

Conclusion

We come to the end of the article on the final keyword in Java. We learned that the final keyword can be used with variables, methods, and classes in Java to serve different purposes.

You can use the final keyword with the variables, classes, and methods in special situations to restrict some things. We discussed how to use a normal variable and reference variable with a final keyword.

We also learned how we can restrict a class from overriding a method. A class can also be made final which ensures that no other class can extend it. This was all about the final keyword in Java.