Junior — Middle
In which situations is it advisable to use the final modifier in code?
sobes.tech AI
Answer from AI
The final modifier in Java is used for:
- Prohibiting method overriding. If a method is declared final, subclasses cannot override it.
- Prohibiting inheritance of classes. A class declared final cannot have subclasses.
- Declaring constants. Final fields cannot change their value after initialization.
It is advisable to use final when you need to guarantee immutability of behavior or data, for example, for security, error prevention, or optimization.
Example:
public final class Constants {
public static final double PI = 3.14159;
}
public class Base {
public final void doSomething() {
// cannot be overridden
}
}