Back to course

The final Keyword: Variables, Methods, and Classes

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 27: The final Keyword

The final keyword is a non-access modifier used to restrict or define something that cannot be changed.

1. final Variables (Constants)

If a variable is declared final, its value cannot be reassigned after initialization. These are often used in conjunction with static to create true compile-time constants.

java // A non-static final variable must be initialized once per object public final int MAX_USERS = 100;

// A standard constant (Convention: static final, SCREAMING_SNAKE_CASE) public static final double INTEREST_RATE = 0.05;

// Example of attempt to reassign: MAX_USERS = 200; // COMPILATION ERROR!

2. final Methods

If a method is declared final, it cannot be overridden by any subclass. This ensures that the method's implementation remains unchanged across the inheritance hierarchy (often used for critical security logic).

java public class Parent { public final void criticalLogic() { // Implementation that must never change } }

public class Child extends Parent { // public void criticalLogic() { /* ERROR! Cannot override final method */ } }

3. final Classes

If a class is declared final, it cannot be extended (cannot have subclasses). This is often done for security reasons or when the design should not allow customization, such as the built-in String class in Java.

java public final class ConfigurationSettings { // ... }

// public class BadAttempt extends ConfigurationSettings { /* ERROR! */ }