Java Lesson 28 – Final | Dataplexa

Final Keyword

The final keyword in Java is used to restrict changes. Once something is marked as final, it cannot be modified further. This helps developers write safer, more predictable, and well-controlled code.

In real-world Java applications, the final keyword is commonly used to protect important values, prevent unwanted inheritance, and ensure that certain logic remains unchanged.


Real-World Meaning of Final

Think of a company policy that cannot be changed once approved. Everyone must follow it exactly as it is.

Similarly, in Java, the final keyword ensures that certain variables, methods, or classes stay exactly as defined.


Final Variables

A final variable can be assigned only once. After that, its value cannot be changed.


class Configuration {

    final int MAX_USERS = 100;

    void showLimit() {
        System.out.println("Maximum users allowed: " + MAX_USERS);
    }
}

Final variables are often used for constants such as limits, settings, and configuration values.


Final Variables in Practice

Trying to change a final variable will result in a compilation error.


MAX_USERS = 200; // ❌ Not allowed

This prevents accidental modification of important values.


Final Methods

A final method cannot be overridden by a child class. This ensures that the method’s behavior remains consistent.


class SecuritySystem {

    final void authenticate() {
        System.out.println("Authentication logic executed");
    }
}

Final methods are often used in security-sensitive logic where behavior must not be altered.


Final Classes

A final class cannot be inherited. This prevents extension and modification of the class behavior.


final class Utility {

    static void showMessage() {
        System.out.println("Utility method");
    }
}

Classes like String in Java are final for safety and performance reasons.


Why Java Uses Final Keyword

The final keyword helps:

  • Protect important logic
  • Prevent accidental overrides
  • Improve code reliability
  • Make programs easier to reason about

It is widely used in frameworks and core Java libraries.


Final vs Static (Common Confusion)

Although final and static are often used together, they serve different purposes:

  • static – belongs to the class
  • final – cannot be changed

A variable can be static, final, or both depending on the requirement.


Best Practices

  • Use final for constants
  • Use final methods for critical logic
  • Use final classes for utility or security classes
  • Avoid unnecessary final usage

Key Takeaways

  • Final restricts modification
  • Final variables cannot be reassigned
  • Final methods cannot be overridden
  • Final classes cannot be inherited

In the next lesson, we will explore inner classes and understand how classes can exist inside other classes.