final keyword is used to provide restriction to classes, methods or variables, ensuring immutability.
uses
- variables - make then constant
- -methods - cannot be overridden
- classes - cannot be inherited.
class Example {
final int MAX_VALUE = 100; // Final instance variable, initialized at declaration
final double PI; // Blank final variable
Example() {
PI = 3.14159; // Initialized in constructor
}
void modify() {
// MAX_VALUE = 200; // Compilation error: Cannot assign a value to final variable
// PI = 3.14; // Compilation error
}
}
class Main {
public static void main(String[] args) {
final int localVar = 10; // Final local variable
// localVar = 20; // Compilation error
System.out.println(localVar); // Output: 10
Example ex = new Example();
System.out.println(ex.MAX_VALUE); // Output: 100
System.out.println(ex.PI); // Output: 3.14159
}
}
- final prevents reassigning the reference but the objects internal state can still be modified.