πΉ final Keyword in Java β The βLast Stopβ π¦
In Java, the final keyword is like putting a βDo Not Change π«β tag on something.
It can be applied to variables, methods, and classes β each with its own purpose.
π Think of it like this:
-
final variable β βThis value is permanent, no one can change it!β
-
final method β βThis method is fixed, no child can override it!β
-
final class β βThis class is sealed, no one can extend it!β
β¨ Uses of final Keyword
1οΈβ£ Final Variable (Constant Value)
Once you assign a value, it cannot be changed.
class Test {
final int SPEED_LIMIT = 100; // Constant
void display() {
// SPEED_LIMIT = 120; β Error β can't change final variable
System.out.println("Speed limit is " + SPEED_LIMIT);
}
}
public class Main {
public static void main(String[] args) {
Test t = new Test();
t.display();
}
}
β Output:
Speed limit is 100
π‘ Tip: Usually written in UPPERCASE to show itβs a constant.
2οΈβ£ Final Method (No Overriding Allowed)
A final method in the parent cannot be overridden by child classes.
class Animal {
final void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
// void sound() { β Error β can't override final method }
}
β This is useful when you want to protect important methods from being modified.
3οΈβ£ Final Class (No Inheritance)
A final class cannot be extended.
final class Vehicle {
void display() {
System.out.println("This is a vehicle");
}
}
// class Car extends Vehicle { β Error β can't inherit final class }
π Example in real Java:
-
The
Stringclass isfinal, so no one can extend it.
π Quick Recap
| Usage | Meaning |
|---|---|
final variable |
Value cannot be changed (constant). |
final method |
Method cannot be overridden by child classes. |
final class |
Class cannot be extended (no inheritance). |
π― Why Learn final?
β Ensures security & integrity of critical code.
β Prevents unwanted modifications.
β Useful for constants, libraries, and frameworks.
π‘ Interview Tip:
π Can we declare a constructor as final?
β No, because constructors are never inherited or overridden.
Β
Β