Junior — Middle
What is the purpose of the 'final' modifier in programming?
sobes.tech AI
Answer from AI
The final modifier in Java is used to restrict modifications:
-
For variables: a variable declared as
finalcannot be reassigned after initialization. -
For methods: a method declared as
finalcannot be overridden in subclasses. -
For classes: a class declared as
finalcannot have subclasses (inheritants).
Example:
final class Constants {
public static final double PI = 3.1415;
}
class Base {
public final void show() {
System.out.println("Final method");
}
}
class Derived extends Base {
// Error: cannot override final method show()
}
final int x = 10;
// x = 20; // Compilation error