Sobes.tech
Junior — Middle

What are the advantages and disadvantages of using the 'final' keyword in Java?

sobes.tech AI

Answer from AI

In Java, the keyword final is used to restrict modifications and inheritance.

Advantages:

  • For variables: the value cannot be changed after initialization, which increases safety and predictability of the code.
  • For methods: the method cannot be overridden in subclasses, helping to preserve logic and prevent errors during inheritance.
  • For classes: the class cannot be inherited, which is useful for creating immutable or extension-protected components.

Disadvantages:

  • It limits the flexibility of the code, as behavior or state cannot be changed after declaration.
  • It may complicate testing and extending functionality.
  • Excessive use of final can lead to overly rigid architecture.

Example:

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

final int maxCount = 10;

final void doSomething() {
    // cannot be overridden
}