DEV Community

PRIYA K
PRIYA K

Posted on

Final Keyword in Java

In Java, final means something cannot be changed further. It can be applied to variables, methods, and classes — but the effect is different in each case.

1. Final Variable
A final variable can be assigned only once. After that, its value cannot change.

class Demo {
    final int age = 20;

    void display() {
        // age = 25;  // Error: cannot change final variable
        System.out.println(age);
    }
}
Enter fullscreen mode Exit fullscreen mode

Why use it?
When you want a constant value, like PI, fixed ID, etc.

Example:

final double PI = 3.14;
Enter fullscreen mode Exit fullscreen mode

2. Final Method
A final method cannot be overridden by a child class.

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

class Child extends Parent {
    // void show() { }   // Error: cannot override final method
}

Enter fullscreen mode Exit fullscreen mode

Why use it?
To prevent subclasses from changing the original behavior of a method.

3. Final Class
A final class cannot be inherited (extended).

final class Vehicle {
    void run() {
        System.out.println("Running");
    }
}

// class Car extends Vehicle { }  // Error: cannot inherit final class
Enter fullscreen mode Exit fullscreen mode

Why use it?
When you want to stop other classes from inheriting it.

A common example is String class in Java — String is final, so no class can extend it.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.