Junior — Middle
What restrictions exist when using the final modifier for methods?
sobes.tech AI
Answer from AI
The final modifier for methods in Java imposes the following restrictions:
- A method declared as
finalcannot be overridden in subclasses. This guarantees that the implementation of the method remains unchanged. - A
finalmethod can be called directly, but its behavior cannot be changed through inheritance. - It is not possible to declare a method as both
abstractandfinal, becauseabstractrequires overriding, whilefinalprohibits it.
Example:
class Parent {
public final void show() {
System.out.println("Final method");
}
}
class Child extends Parent {
// Compilation error: cannot override final method
// public void show() {
// System.out.println("Override");
// }
}
Thus, final methods ensure the immutability of behavior in class hierarchies.