Junior — Middle
What is the purpose of the final modifier in Java and in what situations is its use justified?
sobes.tech AI
Answer from AI
In Java, the final modifier is used for:
- Variables: the value of the variable cannot be changed after initialization.
- Methods: the method cannot be overridden in subclasses.
- Classes: the class cannot be inherited.
The use of final is justified when it is necessary to guarantee immutability of data or behavior, for example:
- Constants declared as
finalto protect against modification. - Methods that should not be overridden to preserve logic.
- Classes that are not intended to be extended, such as
String.
Example:
public final class Constants {
public static final double PI = 3.1415;
}
public class Base {
public final void doSomething() {
// cannot be overridden
}
}