In Java, the final keyword is a modifier that can be applied to classes, methods, and variables, indicating that they cannot be further modified or overridden.
Here's how the final keyword can be used:
When applied to variables, the "final" keyword indicates that the variable can be assigned a value only once.
If a variable is declared "final" and initialized, its value cannot be changed thereafter.
For primitive data types, the value of a "final" variable cannot be altered once assigned.
For reference types (objects), the reference stored in the variable cannot be changed after initialization, but the object's internal state can still be modified.
// value assign to final keyword variable final int age = 20; // re-initialize age variable value // age = 30; Output: error: cannot assign a value to final variable age // value assign to final keyword `userName` variable final String userName = "Alice"; // re-initialize userName variable value // userName = "Jake"; Output: error: cannot assign a value to final variable userName
class Parent { final void display() { System.out.println("Displaying from Parent"); } } class Child extends Parent { // This will result in a compilation error // because 'display' method in Parent is final and cannot be overridden void display() { System.out.println("Displaying from Child"); } }
When applied to methods, the final keyword indicates that the method cannot be overridden by subclasses.
Subclasses cannot provide a different implementation for a final method.
This is often used to prevent modification of critical behaviour in classes that are not intended to be subclassed or to ensure method consistency across subclasses.
final class FinalClass { // Class members and methods } // This will result in a compilation error // because FinalClass is final and cannot be subclassed class SubClass extends FinalClass { // Subclass members and methods }
When applied to classes, the "final" keyword indicates that the class cannot be inherited in subclassed.
Subclasses cannot be created from a "final" class.
Using the final keyword provides certain guarantees in your code, such as immutability of variables, prevention of method overriding, and prohibition of subclassing, which can enhance code safety, stability, and maintainability.