CKTIS / Java
final — restriction on further change
final — restriction on further change: final restricts change: a variable can be assigned once, a method cannot be overridden, and a class cannot be subclassed.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
finalfinal restricts change: a variable can be assigned once, a method cannot be overridden, and a class cannot be subclassed.
Use static final for class constants, a blank final initialized by every constructor, and a final method or class when extension is deliberately closed.
A final reference does not make its object immutable, and a final array still permits element updates; excessive final can unnecessarily constrain design.
An effectively final local can be captured by a lambda without the modifier; final fields receive special visibility guarantees after proper construction.
The final reference still permits adding 2 to the list, while the final method returns fixed and the blank final answer is 7.
Examples
import java.util.ArrayList;
import java.util.List;
public class Main {
static class Base {
final String id() { return "fixed"; }
}
static final class Leaf extends Base {
final int answer;
Leaf(int answer) { this.answer = answer; }
}
public static void main(String[] args) {
final var values = new ArrayList<>(List.of(1));
values.add(2);
Leaf leaf = new Leaf(7);
System.out.println(values);
System.out.println(leaf.id() + ":" + leaf.answer);
}
}
Result
[1, 2] fixed:7
The final reference still permits adding 2 to the list, while the final method returns fixed and the blank final answer is 7.