Final Keyword in Java

What is a final keyword in java?

The final keyword is a non-access modifier used for classes, variables, and methods, which makes them non-changeable (impossible to inherit or override).

Final can be applied with :

  • Java Final Variable:

In java, if we make any variable final then it can’t be modified, or change its value.

Code:

Java Code

class Main {
  public static void main(String[] args) {

    // create a final variable
    final int marks = 12;

    // try to change the final variable
    marks = 87;
    System.out.println("Marks: " + marks);
  }
}

In the above code, we are trying to update the value of marks with new marks but it will give us an error because the final variable once assigned a value can never be changed.

When we try to run the program we will get this compilation error:

error: cannot assign a value to final variable marks
    marks = 87;
    ^
  1 error
  • Java Final Methods:

Before knowing about Java Final methods make sure you are familiar with java inheritance.

Methods marked as final cannot be overridden.

For Example : 

Java Code

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

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

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

In the above code, we try to override our method but by running the code we will get the compilation error:

FinalMethodTuf.java:10: error: show() in Main cannot override show() in FinalMethodTuf
  public final void show() {
                    ^
  overridden method is final
1 error
  • Java Final Class :

In Java, if we try to make our class final, we cannot extend it.

Code:

Java Code

// declaring a final class
final class FinalClassTuf {
  //...
}

class SubclassTuf extends FinalClassTuf{ //attempting to subclass a final class 
throws an error
  //...
}

After running the above code we will get the compilation error :

FinalClassTuf.java:6: error: cannot inherit from final FinalClassTuf
class SubclassTuf extends FinalClassTuf{ //attempting to subclass a final class throws an error
                          ^
1 error

Special thanks to Amisha Kumari for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article