Java final Keyword

Mastering immutability, inheritance prevention, and method restriction

1. The Core Purpose

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.

1. Final Variable

Prevents Re-assignment

Creates constants. Value can only be assigned once.

2. Final Method

Prevents Overriding

Subclasses cannot override or change the logic.

3. Final Class

Prevents Inheritance

Class cannot be extended (e.g., java.lang.String).

2. Code Examples

A. Final Variable (Constant)

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
    }
}

B. Final Method & Class

// 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 {}

3. Interactive Compiler Sandbox

Simulate trying to modify final elements in real time:

Compiler Console Output:

> Click a button above to run code simulation...

4. The Final Reference Object Nuance

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

5. Quick Reference Matrix

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).