Final keyword (final variables, methods, classes)
The final keyword restricts modification. Its meaning depends on where it is applied.
final variables
Section titled “final variables”Cannot be reassigned after initialization. They are constants.
final double PI = 3.14159;PI = 3.14; // compilation error
// Blank final (initialized in constructor)final int MAX_SIZE;MyClass() { MAX_SIZE = 100;}final methods
Section titled “final methods”Cannot be overridden by subclasses.
class Parent { final void display() { System.out.println("Cannot override"); }}class Child extends Parent { // void display() { } // error: cannot override}final classes
Section titled “final classes”Cannot be extended (subclassed).
final class ImmutableClass { // ...}// class SubClass extends ImmutableClass { } // errorUse cases:
finalvariables: for true constants (oftenstatic final)finalmethods: to prevent breaking internal logicfinalclasses: for immutability (e.g.,String,Integer)
Note: final does not make objects immutable; only the reference is fixed.