Sobes.tech
Junior — Middle

In what cases is the final modifier used in Java?

sobes.tech AI

Answer from AI

The final modifier in Java is used in the following cases:

  • For variables: to make them constants, i.e., the value of the variable can only be assigned once. This is useful for immutable data.

  • For methods: to prevent overriding the method in subclasses. This guarantees that the behavior of the method remains unchanged.

  • For classes: to prevent inheritance from this class. This is used when you need to protect the implementation from being changed through inheritance.

Example of using final for a variable:

final int MAX_COUNT = 100;
// MAX_COUNT = 200; // Compilation error

Example for a method:

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

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

Example for a class:

final class Utility {
    // code
}

// class ExtendedUtility extends Utility {} // Error: cannot inherit from a final class