The final
keyword is used to declare constants or prevent modification.
Itβs meaning depends on where its used.
Final Usage Summary
Use With | Effect |
---|---|
Variable | Value cant be changed (constant) |
Method | Method cant be overridden |
Class | Class canβt be extended/inherited |
Example
final int x = 20;
x = 30; // Compilation error
class Animal {
final void sleep() {
System.out.println("Sleeping...");
}
}
class Dog extends Animal {
// Cannot override sleep()
// void sleep() { ... } β Error
}
final class Utility {
// no one can extend this class
}
class MyUtil extends Utility {} // Error
final List<String> list = new ArrayList<>();
list.add("Hello"); // Allowed
list = new ArrayList<>(); // Error
Final object reference = canβt reassign.
But the object itself can still be modified (unless immutable).
Tip
Be ready to explain:
- difference between
final
on primitive vs object reference,- when to use final for immutability, security or clarity,
- why String is final in Java (thread-safety, caching, security).
Parent: _Core