Final Keyword In Java

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

Here we will discuss about the affect of final in on following entities:


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. 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.

  • 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 blaock 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.


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 Parameter in Java

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


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.
  • All variables of an interface is by default final.