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:
finalmeans โ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.