Junior — Middle
For what situations and purposes is the final modifier used in programming?
sobes.tech AI
Answer from AI
The final modifier in Java is used to restrict the modification or overriding of entities:
-
For classes: a class declared as
finalcannot be subclassed. This is useful when you want to prevent extension of a class. -
For methods: a method declared as
finalcannot be overridden in subclasses. This guarantees that the method's implementation remains unchanged. -
For variables: a variable declared as
finalbecomes a constant — its value can only be assigned once.
Example:
final class ImmutableClass {
final int value;
public ImmutableClass(int value) {
this.value = value;
}
public final void display() {
System.out.println("Value: " + value);
}
}
// Attempting to inherit or override methods of this class will cause a compile error.
Using final helps improve code safety, prevent unwanted changes, and enhance readability.