πŸ”Ή final Keyword in Java – The β€œLast Stop” 🚦

In Java, the final keyword is like putting a β€œDo Not Change πŸš«β€ tag on something.
It can be applied to variables, methods, and classes β€” each with its own purpose.

πŸ‘‰ Think of it like this:

  • final variable β†’ β€œThis value is permanent, no one can change it!”

  • final method β†’ β€œThis method is fixed, no child can override it!”

  • final class β†’ β€œThis class is sealed, no one can extend it!”

Generated image

✨ Uses of final Keyword

1️⃣ Final Variable (Constant Value)

Once you assign a value, it cannot be changed.

class Test {
    final int SPEED_LIMIT = 100;  // Constant

    void display() {
        // SPEED_LIMIT = 120; ❌ Error – can't change final variable
        System.out.println("Speed limit is " + SPEED_LIMIT);
    }
}

public class Main {
    public static void main(String[] args) {
        Test t = new Test();
        t.display();
    }
}

βœ… Output:

Speed limit is 100

πŸ’‘ Tip: Usually written in UPPERCASE to show it’s a constant.


2️⃣ Final Method (No Overriding Allowed)

A final method in the parent cannot be overridden by child classes.

class Animal {
    final void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    // void sound() { ❌ Error – can't override final method }
}

βœ” This is useful when you want to protect important methods from being modified.


3️⃣ Final Class (No Inheritance)

A final class cannot be extended.

final class Vehicle {
    void display() {
        System.out.println("This is a vehicle");
    }
}

// class Car extends Vehicle { ❌ Error – can't inherit final class }

πŸ‘‰ Example in real Java:

  • The String class is final, so no one can extend it.


πŸš€ Quick Recap

Usage Meaning
final variable Value cannot be changed (constant).
final method Method cannot be overridden by child classes.
final class Class cannot be extended (no inheritance).

🎯 Why Learn final?

βœ” Ensures security & integrity of critical code.
βœ” Prevents unwanted modifications.
βœ” Useful for constants, libraries, and frameworks.

πŸ’‘ Interview Tip:
πŸ‘‰ Can we declare a constructor as final?
❌ No, because constructors are never inherited or overridden.

Β 

Β