final is used to restrict modification, overriding, or inheritance.

It can be applied to variables, methods, and classes.


1. final Variables

A final variable cannot be reassigned after it has been initialized.

final int age = 20;

age = 25; // ❌ Error

Once a value is assigned, it cannot be changed.

Final Reference Variables

For objects, final prevents changing the reference, not the object's internal state.

final Student student = new Student();

student.name = "Rahul"; // ✅
student = new Student(); // ❌

So:

final reference → cannot point to another object.


2. final Methods

A final method cannot be overridden by a subclass.

class Animal {

    final void eat() {
        System.out.println("Eating");
    }
}

class Dog extends Animal {

    // ❌ Cannot override final method
    // void eat() { }
}

Use final when the parent class wants to prevent subclasses from changing a method's implementation.


3. final Classes

A final class cannot be extended.