![]() |
VOOZH | about |
In Java, the final keyword is used to restrict changes and make code more secure and predictable. It can be applied to variables, methods, and classes to prevent modification, overriding, or inheritance. This helps in creating constant values, stable methods, and immutable classes.
The following are different contexts where the final is used:
The final keyword is used in exactly 3 main contexts:
A variable declared with final becomes constant after one assignment.
Value of PI: 3.14159
A variable declared with final becomes constant after one assignment.
1. final Variable
final int THRESHOLD = 5;
2. Blank final Variable
final int THRESHOLD;
Note: A static final variable must be initialized either at the point of declaration or in a static initialization block.
3. Static final Variable
static final double PI = 3.141592653589793;
4. Static Blank final Variable
static final double PI;
static {
PI = 3.141592653589793;
}
A final reference cannot refer to a new object though the object it points to can change internally.
Geeks GeeksForGeeks
This shows that a final reference cannot point to a different object, but the internal state of the object it points to can still be modified.
Output:
👁 Final Variable Throwing Compile-time Error
A local final variable must be assigned once.
20
A class declared as final cannot be extended. A final class cannot be inherited, meaning no other class can extend it. This is commonly used for security or when the implementation should remain unchanged, such as in core classes like String.
Final classes are useful when creating immutable classes such as String or wrapper classes.
When a method is declared with final keyword, it is called a final method in Java.A final method, on the other hand, can be inherited but cannot be overridden by subclasses, ensuring that the original implementation remains intact.