Let’s explain final
in Java in easy, everyday language — with clear examples so you fully get it.
✅ What Does final
Mean in Java?
In simple terms:
final
means “you can’t change it later.”
It is used when you want to make something unchangeable — like a lock that prevents future changes.
🛠️ Where Can You Use final
in Java?
You can use final
with:
- Variables (can’t change the value)
- Methods (can’t override them)
- Classes (can’t extend/inherit them)
Let’s break them down one by one.
🔹 1. final
Variable
Once you assign a value to a final
variable, you can’t change it.
📦 Example:
public class Demo {
public static void main(String[] args) {
final int speedLimit = 60;
// speedLimit = 80; // ❌ Error: can't change a final variable
System.out.println("Speed Limit is: " + speedLimit);
}
}
✔️ speedLimit
is final — you can set it once, but not change it.
This is useful when you want to declare constants like PI, tax rate, or max limit.
🔹 2. final
Method
You can mark a method as final
so that no subclass can override it.
📦 Example:
class Vehicle {
final void start() {
System.out.println("Vehicle started");
}
}
class Car extends Vehicle {
// void start() { } // ❌ Error: can't override final method
}
✔️ Once a method is marked final
, no class that inherits it can change its behavior.
🔹 3. final
Class
A final
class cannot be extended (inherited).
📦 Example:
final class Animal {
void sound() {
System.out.println("Animal sound");
}
}
// class Dog extends Animal {} // ❌ Error: can't extend a final class
✔️ You use a final
class when you don’t want anyone to change or extend your class — it’s locked.
🔄 Bonus: final
with Objects
If you make an object
final
, you can’t change the object reference, but you can change the data inside.
📦 Example:
public class Demo {
public static void main(String[] args) {
final StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // ✅ Allowed
// sb = new StringBuilder("Hi"); // ❌ Not allowed
System.out.println(sb); // Output: Hello World
}
}
✔️ The object is final — you can’t reassign it — but you can change what’s inside it.
🧠 Summary
Use of final | What it does | Example |
---|---|---|
Variable | Can’t change its value | final int x = 10; |
Method | Can’t override it in subclass | final void run() |
Class | Can’t be extended (inherited) | final class Animal |
🎯 Think of final
as:
- A lock 🔒 — once used, no one can change or override it.
- A way to protect values, methods, or class designs.