Sobes.tech
Junior — Middle

What is the purpose of the 'final' modifier in programming?

sobes.tech AI

Answer from AI

The final modifier in Java is used to restrict modifications:

  • For variables: a variable declared as final cannot be reassigned after initialization.

  • For methods: a method declared as final cannot be overridden in subclasses.

  • For classes: a class declared as final cannot have subclasses (inheritants).

Example:

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

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

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

final int x = 10;
// x = 20; // Compilation error
What is the purpose of the 'final' modifier in… - sobes.tech