Final Keyword in Java
Final Keyword in Java
The final keyword in Java is used to restrict modification.
It can be applied to:
- Variables (values cannot be changed)
- Methods (cannot be overridden)
- Classes (cannot be inherited)
Final Variables
A variable declared final becomes constant — you must assign a value, and it cannot change after assignment.
Example:
final int x = 10;
// x = 20; // ❌ Error: cannot assign a value to final variable
Final Reference Variable
If the variable is a reference type, the object it points to can still be modified, but the reference itself cannot change.
final int[] arr = {1, 2, 3};
arr[0] = 10; // ✅ Allowed
// arr = new int[5]; // ❌ Not allowed
Final Methods
A method marked final cannot be overridden by subclasses.
Example:
class Animal {
final void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
// void sound() {} // ❌ Error: Cannot override final method
}
Final Classes
A class declared as final cannot be extended.
Example:
final class Vehicle {
void run() {
System.out.println("Vehicle is running");
}
}
// class Car extends Vehicle {} // ❌ Error: Cannot subclass final class
Summary Table
final Applied To |
Meaning |
---|---|
Variable | Constant value (cannot be reassigned) |
Method | Cannot be overridden |
Class | Cannot be extended (no subclasses) |
When to Use final
Use Case | Why |
---|---|
Constants | Ensure values like PI , MAX_LIMIT , etc. don’t change |
Prevent Inheritance | Improve security and avoid misuse |
Immutable Classes | Build classes like String , which can't be modified |