The final Keyword

Site Admin · 11 Sep 2026 · 9 views

Three Jobs of final

The final keyword makes something unchangeable. Where it applies changes its meaning.

Final Variables (Constants)

final double PI = 3.14159;
PI = 3.0; // compile error - cannot reassign

class Config {
    static final int MAX_USERS = 500;   // typical constant
}

Note: final on a reference type prevents re-pointing the reference; the object itself can still change.

final StringBuilder sb = new StringBuilder("A");
sb.append("B");   // allowed: object changes
// sb = new StringBuilder();  // not allowed: reference fixed

Final Methods

A final method cannot be overridden by a subclass:

class Vehicle {
    final void vin() { System.out.println("VIN-001"); }
}
// no subclass may override vin()

Final Classes

A final class cannot be extended. For example, String and Integer are final.

final class MathUtils { ... }
class BetterMath extends MathUtils { } // compile error

Final Parameters and Local Variables

void greet(final String name) {
    // name cannot be reassigned inside the method
    System.out.println("Hello " + name);
}

Key Points

  • final variable: cannot reassign.
  • final method: cannot override.
  • final class: cannot extend.
  • Only a final reference, not the object it points to, is frozen.
Share this post:

Comments (0)

Please login or register to comment.