In Java, the final keyword is used to stop changes.
It can be used with variables, methods, and classes.
- If a variable is final, its value cannot be changed.
- If a method is final, it cannot be overridden.
- If a class is final, it cannot be inherited.
1. Final Variable
A final variable can only be assigned once.
final int x = 10;
x = 20; // Error: cannot change value
- Acts like a constant
- Must be initialized once (either at declaration or in constructor)
2. Final Method
A final method cannot be overridden by subclasses.
class Parent {
final void show() {
System.out.println("Final method");
}
}
class Child extends Parent {
void show() { // Error
System.out.println("Cannot override");
}
}
3. Final Class
A final class cannot be inherited (extended).
final class Animal {}
class Dog extends Animal { // Error
}
Example:
-
Stringclass in Java is final
Top comments (0)