final KeywordMastering immutability, inheritance prevention, and method restriction
In Java, the final keyword is a non-access modifier used to apply restrictions on entities. Think of it as a way to make something unchangeable once declared.
Prevents Re-assignment
Creates constants. Value can only be assigned once.
Prevents Overriding
Subclasses cannot override or change the logic.
Prevents Inheritance
Class cannot be extended (e.g., java.lang.String).
public class MathUtils {
// Static final = global constant convention
public static final double PI = 3.14159;
public void test() {
final int maxAge = 100;
// maxAge = 105; // ❌ COMPILER ERROR: Cannot assign a value to final variable
}
}
// Final Class cannot be extended
public final class SecuritySystem {
public final void authenticate() {
System.out.println("Core security logic running...");
}
}
// ❌ COMPILER ERROR: Cannot inherit from final SecuritySystem
// class CustomSecurity extends SecuritySystem {}
Simulate trying to modify final elements in real time:
A common interview trap: Making an object reference final stops you from pointing to a new object, but it does NOT stop you from modifying the object's internal fields!
final List<String> names = new ArrayList<>();
names.add("Alice"); // ✅ ALLOWED: Internal state modified
names.add("Bob"); // ✅ ALLOWED: Object is mutable
// names = new ArrayList<>(); // ❌ COMPILER ERROR: Re-assigning reference
| Applied To | Primary Benefit | Key Constraint |
|---|---|---|
| Variable | Immutability / Constants | Value cannot be reassigned after initialization. |
| Method | Security / Design Integrity | Child classes cannot override the method. |
| Class | Security / Immutability | Class cannot be extended (`extends` keyword fails). |