DEV Community

Arun Kumar
Arun Kumar

Posted on

Final keyword in java

The final keyword in Java is a non-access modifier used for variables, methods, and classes. It means "cannot be changed".

🔹 1. final Variable

Once assigned, its value cannot be changed.
Used for constants.

final int MAX_USERS = 100;
// MAX_USERS = 200; ❌ Error: can't assign a new value
Enter fullscreen mode Exit fullscreen mode

✅ Use it when you want a value to stay constant (like configuration values, limits, etc.)

🔹 2. final Method

A method declared as final cannot be overridden by subclasses.

class Parent {
    final void display() {
        System.out.println("Parent display");
    }
}

class Child extends Parent {
    // void display() ❌ This will cause an error
}
Enter fullscreen mode Exit fullscreen mode

✅ Use it when you want to protect method behavior from being changed in child classes.

🔹 3. final Class

A class marked as final cannot be inherited. Eg:

final class Vehicle {
    // ...
}

// class Car extends Vehicle ❌ Error: can't extend final class

Enter fullscreen mode Exit fullscreen mode

✅ Use it when you want to prevent inheritance, usually for security

Top comments (0)