Final Keyword In Java With Examples

In java final is a keyword or reserved word and can be applied to variables, methods, classes etc. The reason behind final keyword is to make entity non modifiable. It means when you make a variable or class or method as final you are not allowed to change that variable or class or method and compiler will verify this and gives compilation error if you try to re-initialized final variables in java.

The final keyword in java is used to give restriction to the user. The java final keyword can be used in many contexts. Final can be:

  • variable
  • method
  • class

Important Note: The final keyword can be used with the variables and a final variable that have no value is known as blank final variable. It can be initialized or declared in the constructor only. The blank final variable can be static also which means it will be initialized in the static block only.


Table of Contents

Final Variable

Any variable which is declared by using the final keyword is called final variable. Final variables can be declare with static keyword in java and treated as constant. A final variable can only be explicitly assigned once.

However the data within the object can be changed. So the state of the object can be changed but not the reference.

Program Example of Final Variable:

This program example shows how to declare final variable in a java class.

class FinalVariable

{

   public static void main(String[] args)

   {

      final int hours=24;

      System.out.println("Hours in 6 days = " + hours * 6);

   }

}

Output:

Hours in 6 days = 144

Another program example of final variable:

The below program shows how final variable value cannot be changed. It gives compilation error if we want to change the value of final variable:

class FinalVariable1

{

   public static void main(String args[])

  {

    final int i = 30;

    i = 60;

  }

}

Output:

Compiler Error: cannot assign a value to final variable i

Important Note: Final variables are by default read-only.


Final method

Sometimes we may want to prevent a childclass to overriding a method from parentclass. To do this we use final keyword with method declaration. It means a method with final keyword is called final method. Final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded on compile time.

The main reason behind making a method final would be that the content of the method should not be changed by any outsider.

Important Note: Any attempt to override the final method will result in compilation error.

Program Example of Final Method:

Let us take an example to understand the use of final method.

Step 1: First we create a class X in which we declare the final method getMethod():

class X

{

  final void getMethod()

  {

    System.out.println(“X method has been called”);

  }

}

Step 2: Second we create a class Y which extends the class X and here we try to override the method of above class:

class Y extends X

{

  void getMethod() //cannot override

  {

    System.out.println(“Y method has been called”);

  }

}

Step 3: Third we create a class FinalMethod in which we create an object of class Y:

class FinalMethod

{

  public static void main(String[] args)

  {

    Y obj = new Y();

    obj.getMethod();

  }

}

Explanation:

On compiling the above program, it will display an compilation error “getMethod() in Y cannot override getMethod() in X; overridden method is final.”


Final Class

A class with final keyword is known as final class in java. Final class is complete in nature and cannot be inherited. Several classes in Java are final e.g. String, Integer and other wrapper classes.

The main purpose or reason of using a final class is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class.

Program Example of Final Class:

Let us take a program example to show the use of final class.

Step 1: First we create a class X and make it final class by using final keyword:

final class X

{

  //properties and methods of class X

}

Step 2: Second we create a class Y which is trying to extend final class X:

class Y extends X

{

  //properties and methods of class Y

}

Step 3: Third we create a class FinalClass:

class FinalClass

{

   public static void main(String args[]) {}

}

Output:

Compiler Error: cannot inherit from final X

Importance of final keyword:

  • Final keyword helps in improving performance.
  • Final variables are safely shared in multithreading environment without additional synchronization overhead.
  • Final keyword allows JVM to optimized method, variable or class.

Important Points to Remember About Final Keyword

  • Constructors cannot be final.
  • If you make any class as a final then it cannot be inherited that means to stop inheritance make a class final.
  • If you make any data members as a final then it will become constant that means you cannot change value of this variable throughout the function.
  • If you make static data member of a class a final then it will become constant that means you cannot change the value of this variable throughout the class and it has to be initialized at class level.
  • If you make any non static data member of a class as a final then it will also become constant that means you cannot change the value of variable throughout the class and it has to be initialize at class level.
  • If you want to make any non static data member as a blank final variable then it has to be initialized via constructor only.
  • By default all the data members of an interface are final and static also.