Sobes.tech
Junior — Middle

What is the role and purpose of the keyword final in the programming language?

sobes.tech AI

Answer from AI

In Java language, the keyword final is used to denote entities that cannot be changed after initialization:

  • final variable: the value cannot be changed after assignment.
  • final method: the method cannot be overridden in subclasses.
  • final class: the class cannot be inherited.

Example:

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 show()
}

Using final helps ensure immutability and code safety.