Final Keyword In Java

final keyword in Java is used to impose various restriction on variables, methods, classes and method parameters. Keyword final enforces different restrictions depending on the type of entity it is applied on.

Once we declared an entity(like variable, method or class) as final, it can be assigned only once.

  • A final variable in java can be initialized only once, we cannot reinitialize it with another value.
  • A final method in java cannot be overridden.
  • A final class in java cannot be extended.
Java final keyword
Here we will discuss about the affect of final on these entities in detail.


final Variable in Java

A variable declared with final keyword is known as final variable.A final variables is a constant whose value cannot be changed after initialization. If, we try to change the value of a final variable in our program then it will generate a compilation error.
We use final variables to define constants like rate of interest, value of PI, coefficient of friction etc.

public class FinalVariable {
    public static void main(String[] args) {
        // Final variable
        final int count = 100;
        // updating final variable value
        count = 150;
        System.out.println("Count = " + count);
    }
}
Output
cannot assign a value to final variable count
  • Blank final variable in Java
    A final variable which is not initialized during initialization is known as blank final variable. Blank final variables must be initialized inside constructor to avoid compilation error.We use blank final variable to store constant values which is specific to every object. Every object will have it's own value of this constant, but once assigned it cannot be changed later.

    For Example: We have a final variable employeeId inside class Employee. As every employee will have it's own unique constant employee Id, we will set employeeId field inside constructor of class Employee. We cannot initialize employeeId with some constant for all employees and it is unique for all employees.

  • Blank static final variable in Java
    A blank static final variable is a class variable(shared by al objects of class) not an instance variable. If we don't initialize a block static variable during declaration then we must initialize it inside a static block.

final Method in Java

A method declared with final keyword is known as final method. A final method cannot be overridden. It means a subclass cannot override a final method of parent class. If a subclass tries to override final method then it will generate a compile time error.

A subclass can invoke final method of parent class but cannot override it.

class BaseClass {
    public final void printMessage() {
        System.out.println("Message from Base class");
    }
}

class SubClass extends BaseClass{
    public final void printMessage() {
        System.out.println("Message from Sub class");
    }
}

public class FinalMethod {
    public static void main(String[] args) {
        SubClass subClass = new SubClass();
        subClass.printMessage();
    }
} 
Output
printMessage() in SubClass cannot override printMessage() in BaseClass
overridden method is final

In the above program, we have created a final method called printMessage inside "BaseClass". "SubClass" inherits "BaseClass" class and override printMessage method. When we run this program, we will get a compilation error saying we cannot override a final method.


final Class in Java

A class declared with final keyword is known as final class. A final class cannot be inherited by any class. When we want to make a class non extensible then we make it a final class.

final class BaseClass {
    public void printMessage() {
        System.out.println("Message from Base class");
    }
}

class SubClass extends BaseClass{
    public void printMessage() {
        System.out.println("Message from Sub class");
    }
}

public class FinalClass {
    public static void main(String[] args) {
        SubClass subClass = new SubClass();
        subClass.printMessage();
    }
}
Output
cannot inherit from final BaseClass

In the above program, we have created a final class called "BaseClass". "BaseClass" tried to inherits the final class "BaseClass". When we run this program, we will get a compilation error saying we cannot inherit from a final class.


final Parameter in Java

If we declare a method parameter as final the we cannot change the value of parameter inside method body.

public class FinalMethodParameter {
    public static int increment(final int num) {
        // incrementing final parameter num
        num = num + 1;
        return num;
    }

    public static void main(String[] args) {
        int var = 10;
        increment(var);
        System.out.println(var);
    }
}
Output
final parameter num may not be assigned

In the above program, we have created a method called increment with a final integer parameter num. We try to increment the value of num inside method body. When we run this program, we will get a compilation error saying "final parameter num may not be assigned".


Best Practices of Using Final Keyword in Java

  • Finalization and Garbage Collection : It's essential to note that the final keyword, when applied to a variable, does not make the object itself immutable. It merely makes the variable reference immutable. The state of the object it references can still be modified.

  • Final Fields and Constructor Initialization : When using final fields in a class, it's a good practice to initialize them in the constructor. This ensures that the final fields are assigned a value before any other methods can access them.

  • Final Classes and Method Overriding : When a class is marked as final, all its methods are implicitly final as well. This means that even if you don't explicitly mark methods as final within a final class, they cannot be overridden by subclasses.

  • Use Final Where Appropriate : While the final keyword offers benefits in terms of immutability, security, and predictability, it's essential to use it judiciously. Applying final indiscriminately can lead to rigid and less maintainable code. Consider the specific requirements of your classes, variables, and methods before using the final keyword.

  • Immutability vs. Finality : While final variables contribute to immutability, not all immutable variables are declared as final. Immutable objects can be achieved through other means, such as using the final keyword for fields, constructor-based initialization, and avoiding mutator methods.

Points to remember about final Keyword in Java
  • A final variable is a constant.
  • A local final variable must be initialized at the time of declaration.
  • A blank final variable must be initialized inside constructor.
  • A static blank final variable must be initialized inside static block.
  • A final method cannot be overridden by a subclass, however subclass can invoke final method of parent class.
  • A constructor method cannot be final.
  • A final class cannot be inherited.

Conclusion

The final keyword in Java is a versatile tool for enforcing constraints and promoting certain programming practices. Whether applied to variables, methods, or classes, it contributes to the creation of robust, secure, and maintainable code. By understanding the different use cases and best practices associated with the final keyword, Java developers can leverage its benefits to enhance the quality of their code and design classes and systems that are resistant to unintended modifications.