library
beginnerThe final Keyword: Variables, Methods & Classes
Understand the three uses of final and their implications for immutability, inheritance, and performance.
final has three uses in Java:
final variable = a permanent marker (write once, can't erase). final method = a company policy (branches can't override HQ rules). final class = a sealed blueprint (no modifications allowed, build as-is).
Key Concepts
1
1. final variables: value cannot be reassigned after initialization.
- Local variables: must be assigned exactly once
- Fields: must be initialized in constructor or declaration
- Method parameters: can't be reassigned in the method body
- Note: final only prevents reassignment of the reference — the object itself can still be mutated (final List<String> list — can add to list, can't reassign list)
2
2. final methods: cannot be overridden by subclasses.
- Prevents subclass from changing behavior
- private methods are implicitly final
- Template Method pattern: make the template final, let subclasses override hook methods
3
3. final classes: cannot be extended.
- No subclasses allowed
- String, Integer, all wrapper classes are final
- Records are implicitly final
- Sealed classes' permitted subclasses are often final
4
Effectively final (Java 8): a variable that is never reassigned after initialization is 'effectively final' — usable in lambdas and anonymous classes even without the final keyword.
5
Performance: final fields enable JVM optimizations (constant folding, safe publication in constructors). final methods can be inlined by the JIT compiler. But modern JITs are smart enough that explicit final rarely matters for performance.