Java final keyword

In Java, the final keyword is used to indicate that a variable, method, or class cannot be modified or extended after it has been initialized or declared. The final keyword has the following characteristics:

  • A final variable cannot be reassigned a new value after it has been initialized.
  • A final method cannot be overridden by a subclass.
  • A final class cannot be extended by another class.

Here are some examples of using the final keyword in Java:

Example 1: Final variable

refer ‮tfigi:ot‬idea.com
class MyClass {
    private final int x = 10;
    
    public void printX() {
        System.out.println(x);
    }
}

In the example above, the x variable is declared as final, which means it cannot be reassigned a new value after it has been initialized to 10.

Example 2: Final method

class MyClass {
    public final void printMessage() {
        System.out.println("Hello World!");
    }
}

class MySubclass extends MyClass {
    // this will generate a compile-time error, as the final method cannot be overridden
    public void printMessage() {
        System.out.println("Goodbye World!");
    }
}

In the example above, the printMessage method in the MyClass class is declared as final, which means it cannot be overridden by a subclass. When MySubclass tries to override the method, it will generate a compile-time error.

Example 3: Final class

final class MyClass {
    // class body
}

// this will generate a compile-time error, as the final class cannot be extended
class MySubclass extends MyClass {
    // subclass body
}

In the example above, the MyClass class is declared as final, which means it cannot be extended by another class. When MySubclass tries to extend the class, it will generate a compile-time error.

Using the final keyword can provide additional safety and clarity to the code. It can also help with performance optimization by allowing the compiler to make assumptions about the value of a final variable or the behavior of a final method.