final is used to restrict modification, overriding, or inheritance.
It can be applied to variables, methods, and classes.
final VariablesA 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.
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:
finalreference → cannot point to another object.
final MethodsA 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.
final ClassesA final class cannot be extended.