Junior
In what cases can the final modifier be used in Java?
sobes.tech AI
Answer from AI
The final modifier in Java can be applied to:
- Variables:
- If the variable is of a primitive type, its value cannot be changed after initialization.
- If the variable is of a reference type, the reference cannot be changed after initialization (the object cannot be reassigned), but the contents of the object can be modified.
- Methods:
- A method declared with the
finalmodifier cannot be overridden in subclasses.
- A method declared with the
- Classes:
- A class declared with the
finalmodifier cannot have subclasses (cannot be inherited).
- A class declared with the
Examples of usage:
// final primitive variable
final int MAX_VALUE = 100;
// final reference variable
final List<String> names = new ArrayList<>();
names.add("Alice"); // Modifying the object's contents is allowed
// names = new LinkedList<>(); // Reassignment is not allowed
// final method
public final void processData() {
// method logic
}
// final class
public final class ImmutableClass {
// fields and methods
}
Using final helps to:
- Ensure data immutability.
- Prevent unwanted method overriding or class inheritance.
- Allow the compiler to perform optimizations.
- Improve code readability by explicitly indicating restrictions.