Junior — Middle
In which cases is it advisable to use the final modifier in programming?
sobes.tech AI
Answer from AI
The final modifier in Java is used to restrict inheritance and overriding:
- final class cannot be inherited. It is used when you want to prevent class extension (for example, for security or to maintain immutable behavior).
- final method cannot be overridden in subclasses. This guarantees that the method's implementation remains unchanged.
- final variable — its value cannot be changed after initialization, which is useful for constants and ensuring immutability.
Example:
final class Constants {
public static final double PI = 3.1415;
}
class Base {
public final void show() {
System.out.println("Base show");
}
}
class Derived extends Base {
// Error: cannot override final method
// public void show() { }
}
Using final helps improve code safety and prevents unintended modifications.