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
✅ 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
}
✅ 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
✅ Use it when you want to prevent inheritance, usually for security or design reasons (e.g., String class is final).
🔹 Bonus: final with reference types
If you declare an object as final, the reference cannot be changed, but the object’s internal state can still be changed.
EX:
final List list = new ArrayList<>();
list.add("Hello"); // ✅ okay
list = new ArrayList<>(); // ❌ error