Junior — Middle
What is the purpose and use of the final keyword in programming?
sobes.tech AI
Answer from AI
In Java, the final keyword is used to restrict modifications and ensure immutability in different contexts:
-
For variables: a variable declared as
finalcannot be reassigned after initialization. This guarantees that the value remains constant. -
For methods: a method declared as
finalcannot be overridden in subclasses, which helps protect the method implementation from changes. -
For classes: a class declared as
finalcannot be subclassed, meaning you cannot create a subclass of such a class.
Example of usage:
final int MAX_COUNT = 10;
final class Utility {
public final void doSomething() {
// implementation
}
}
// Attempting to extend Utility will cause a compile-time error
// class ExtendedUtility extends Utility {} // Error