final Keyword

In Java, the final keyword is used to declare constants, prevent method overriding, and prevent inheritance. It plays a key role in ensuring immutability and maintaining control over how classes and methods are used.

Final Variables

When a variable is declared as final, its value cannot be changed after it is initialized. Essentially, it becomes a constant. This is particularly useful when you need to maintain fixed values throughout your code.

Example:

Final Methods

A final method cannot be overridden by subclasses. This ensures that the behavior of the method remains consistent, even in derived classes.

Example:

Final Classes

A final class cannot be subclassed. This is useful when you want to create a class that should not be extended, ensuring that its behavior remains unchanged.

Example:

Why Use final ?

  • Immutability: Helps create unchangeable variables, ensuring consistency.
  • Security: Prevents method or class modifications, which can be useful for critical systems.
  • Performance: Some optimizations can be performed by the compiler when it knows a method or variable is final.