final Variable
Definition:
A final variable is a constant. Once assigned, its value cannot be changed.
• It is used to make a variable as a constant, Restrict method overriding, Restrict
inheritance.
• It is used at variable level, method level and class level. In java language final keyword
can be used in following way.
Element Description Can it be changed/extended?
final variable Value cannot be changed ❌ No reassignment
final method Cannot be overridden in subclass ❌ No overriding
final class Cannot be extended ❌ No inheritance
Example:
Final at Variable Level :
• Final keyword is used to make a variable as a constant.
• This is similar to const in other language. A variable declared with the final keyword
cannot be modified by the program after initialization.
public class FinalVariableExample {
public static void main(String[] args) {
final int MAX_VALUE = 100;
// MAX_VALUE = 200; // ❌ Error: Cannot assign a value to final variable
[Link]("Max value: " + MAX_VALUE);
}
}
✅ 2. final Method
Definition:
A final method cannot be overridden by subclasses. It ensures that the method’s behavior
remains unchanged.
1. It makes a method final, meaning that sub classes can not override this method.
2. The compiler checks and gives an error if you try to override the method.
3. When we want to restrict overriding, then make a method as a final.
Example:
class Parent {
final void display() {
[Link]("Final method in Parent");
}
}
class Child extends Parent {
// void display() { // ❌ Error: Cannot override the final method
// [Link]("Trying to override");
// }
}
✅ 3. final Class
Definition:
A final class cannot be extended (inherited). It prevents other classes from creating
subclasses.
Example:
final class FinalClass {
void show() {
[Link]("Inside FinalClass");
}
}
// class SubClass extends FinalClass { // ❌ Error: Cannot subclass the final class
// }
public class FinalClassExample {
public static void main(String[] args) {
FinalClass obj = new FinalClass();
[Link]();
}
}