The final keyword in Java is used to declare constants, prevent inheritance, and restrict method overriding. It can be applied to variables, methods, and classes.
Usage:
1. Final Variables: Once assigned, their value cannot be changed.
final int MAX_VALUE = 100;
2. Final Methods: Prevent method overriding in subclasses.
class Parent {
final void display() {
System.out.println(“This cannot be overridden.”);
}
}
3. Final Classes: Prevent inheritance, meaning no other class can extend it.
final class Utility {
// Class code
}
The final keyword enhances code stability by ensuring constants remain unchanged, preventing unwanted modifications in inheritance, and preserving method behaviors in base classes.