0
0
JavaConceptBeginner · 3 min read

What is final keyword in Java: Explanation and Examples

In Java, the final keyword is used to declare constants, prevent method overriding, and stop inheritance of classes. It means the value or behavior cannot be changed once assigned or defined.
⚙️

How It Works

Think of the final keyword as a 'lock' that stops changes. When you mark a variable as final, you are saying, "This value is fixed and cannot be changed." It's like writing with permanent ink instead of pencil.

For methods, final means no one can change how that method works in child classes. For classes, it means no other class can inherit or extend it. This helps keep important parts safe from accidental changes.

💻

Example

This example shows a final variable, a final method, and a final class.

java
public final class FinalExample {
    public final int constantValue = 10;

    public final void showMessage() {
        System.out.println("This method cannot be overridden.");
    }

    public static void main(String[] args) {
        FinalExample example = new FinalExample();
        System.out.println("Constant value: " + example.constantValue);
        example.showMessage();

        // example.constantValue = 20; // Error: cannot assign a value to final variable
    }
}

// The following class would cause an error because FinalExample is final
// class ChildExample extends FinalExample {}
Output
Constant value: 10 This method cannot be overridden.
🎯

When to Use

Use final when you want to protect important data or behavior from changing. For example:

  • Declare constants like final double PI = 3.14; so the value stays the same.
  • Prevent methods from being changed in subclasses to keep core logic safe.
  • Make classes final when you want to stop others from extending them, ensuring your design stays intact.

This helps avoid bugs and keeps your code predictable and easier to understand.

Key Points

  • final variables must be assigned once and cannot change.
  • final methods cannot be overridden by subclasses.
  • final classes cannot be extended.
  • Using final improves code safety and clarity.

Key Takeaways

The final keyword locks variables, methods, or classes to prevent changes.
Use final variables for constants that never change.
Mark methods final to stop overriding and classes final to stop inheritance.
Final helps keep your code safe, clear, and bug-free.