final (Java)
In Java, final
is a non-access modifier that has different meanings depending on the context in which it is used. It's a keyword used to indicate that a variable, method, or class cannot be changed or overridden.
Final Variables:
When final
is applied to a variable, it means that the variable's value cannot be changed once it has been initialized. In essence, it becomes a constant after its first assignment. final
variables must be explicitly initialized, either at the point of declaration or within a constructor (for instance variables). Failure to initialize a final
variable will result in a compile-time error. Once initialized, attempting to reassign a value to a final
variable will also produce a compile-time error. For object references that are final
, the reference itself cannot be changed to point to a different object, but the state of the object the reference points to can be modified (unless the object itself is immutable).
Final Methods:
A final
method cannot be overridden by subclasses. This is often used to prevent unwanted modifications to a method's behavior in derived classes. Declaring a method as final
essentially freezes its implementation within the class where it's defined. Subclasses can still inherit and use the method, but they cannot provide their own version through overriding. This can be useful for enforcing specific behavior across an inheritance hierarchy.
Final Classes:
Declaring a class as final
prevents it from being subclassed. This means that no other class can extend a final
class. This is commonly used when the class's implementation is complete and you don't want other classes to inherit from it. Final classes are implicitly final
in all aspects of their functionality. Effectively, it creates a terminal point in any potential inheritance hierarchy.