What is the purpose of the final keyword in Java?
The final keyword in Java is a non-access modifier used to impose restrictions on variables, methods, and classes. Its main purposes include:
Final Variable:
When a variable is declared as final, its value cannot be changed once assigned. This is often used to create constants.
final int MAX_VALUE = 100; // Constant
Final Method:
A final method cannot be overridden by subclasses. This ensures the method’s behavior remains unchanged in derived classes.
class Parent {
final void display() {
System.out.println(“This cannot be overridden.”);
}
}