Final Keyword in Java

final is a keyword or a non-access modifier in Java and it is applicable to a class, a method and a variable.

Final Keyword in Java, Final Variables in Java, Final Methods in Java, Final Class in Java

Final Variable in Java

When a variable is declared as final then we cannot perform any changes on the existing value of that variable. We use the final variable to declare constant.

While creating a variable as final it is advised to declare the complete variable name in upper case and use underscore character to separate the words.

Syntax

public final MAX_VALUE = 10;

A final variable must be initialized otherwise we will get compile time error. We can initialize a final variable only once via initializer or assignment statement.

Example of the Final Variable

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

  {
    final int D = 20;
    D = 10;
  }

}
Example Output

Final Methods in Java

When a method is declared as final then this method cannot be overridden in child class. We must declare methods as final when we want to restrict child classes to override the method and want to let derive the same implementation of the parent method.

Example of the Final Method

class A 
{
    final void m1() 
    {
        System.out.println("This is a final method.");
    }
}

class B extends A 
{
    void m1()
    { 
        // COMPILE-ERROR! Can't override.
        System.out.println("Illegal!");
    }
}
Example Output

Final Class in Java

When we declare a class as final then this class cannot be extended.
There are two uses of final class –

The first use is for preventing inheritance, as final classes cannot be extended. For example, all wrapper classes like String, Integer, Float, and Double are final classes. And we cannot extend them.

Example of the Final Class

Example:
final class A
{
     // methods and fields
}
// The following class is illegal.
class B extends A 
{ 
    // COMPILE-ERROR! Can't subclass A
}

Another use is to create an immutable class like the predefined String class.

Share