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:
1 2 |
final int MAX_USERS = 100; MAX_USERS = 200; // Error: cannot assign a value to a final variable |
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:
1 2 3 4 5 6 7 8 9 10 11 |
class Parent { public final void display() { System.out.println("This is a final method."); } } class Child extends Parent { public void display() { // Error: cannot override final method System.out.println("Attempting to override."); } } |
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:
1 2 3 4 5 6 |
final class Immutable { // Class definition } // Error: Cannot subclass a final class class ExtendedImmutable extends Immutable {} |
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
.