Sobes.tech
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 final cannot be overridden in subclasses. This guarantees that the implementation of the method remains unchanged.
  • A final method can be called directly, but its behavior cannot be changed through inheritance.
  • It is not possible to declare a method as both abstract and final, because abstract requires overriding, while final prohibits 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.