Sobes.tech
Junior — Middle

In what situations and for what purposes is the final modifier used in code?

sobes.tech AI

Answer from AI

The final modifier in Java is used to restrict modifications and enhance code safety:

  • For variables: a variable declared as final can only be initialized once. This is useful for creating constants or preventing accidental changes to the value.

  • For methods: a method declared as final cannot be overridden in subclasses. This ensures that the method's behavior remains unchanged.

  • For classes: a class declared as final cannot be inherited. This is used when you want to prevent extension of the class, for example, to ensure security or integrity of logic.

Example:

public final class Constants {
    public static final double PI = 3.14159;
}

class Base {
    public final void show() {
        System.out.println("Final method");
    }
}

class Derived extends Base {
    // Error: cannot override final method
    // public void show() { }
}