Sobes.tech
Junior — Middle

What is the purpose of the final modifier when declaring a function in Java?

sobes.tech AI

Answer from AI

The final modifier when declaring a function in Java means that this method cannot be overridden in subclasses. It is used to prevent changing the behavior of the method in inheritors, which can be important for maintaining logic or security of the code.

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("Attempt to override");
    // }
}
What is the purpose of the final modifier when… - sobes.tech