: Final can be applied to classes, methods and variables and the features cannot be
changed. Final class cannot be subclassed, methods cannot be overridden.
In Java, the final
modifier is used to apply restrictions on classes, methods, and variables. Here’s a brief explanation of its usage in different contexts:
- Final Variables:
- When applied to a variable, the
final
keyword ensures that the value of the variable cannot be changed once it has been assigned. It essentially makes the variable a constant. - Example:
java
final int MAX_VALUE = 100;
// MAX_VALUE cannot be reassigned a new value
- When applied to a variable, the
- Final Methods:
- When applied to a method, the
final
keyword indicates that the method cannot be overridden by subclasses. It is a way to prevent further modification of a method in a subclass. - Example:
java
class Child extends Parent {class Parent {
final void display() {
System.out.println("This method cannot be overridden.");
}
}
// Error: Cannot override the final method from Parent
/*void display() {
// Some implementation
}*/
}
- When applied to a method, the
- Final Classes:
- When applied to a class, the
final
keyword indicates that the class cannot be subclassed. It ensures that no other class can extend it. - Example:
java
// Error: Cannot inherit from final classfinal class FinalClass {
// Class members and methods
}
/*class SubClass extends FinalClass {
// Some implementation
}*/
- When applied to a class, the
In summary, the final
modifier in Java is used to make variables, methods, and classes immutable or unmodifiable, depending on where it is applied.