Skip to content

What is the point of "final class" in Java?

In Java, a class can be marked as final, which means that it cannot be subclassed. This can be useful in a number of situations:

  • To prevent others from extending your class and potentially introducing incompatible changes. This can be especially useful if your class has a well-defined interface that you want to maintain.
  • To guarantee the behavior of your class remains consistent. Since it cannot be subclassed, you can be certain that no one will override its methods to alter its core functionality.
  • To enforce design constraints. Marking a class as final clearly communicates that it is complete and not intended for extension.

It is important to note that all methods in a final class are implicitly final and cannot be overridden, since the class itself cannot be extended.

Here is an example of a final class in Java:


java
final class MyClass {
  private final String value;

  public MyClass(String value) {
    this.value = value;
  }

  public String getValue() {
    return value;
  }
}

You can then use the class as you would any other class, but it cannot be subclassed. A common real-world example is java.lang.String, which is declared as final to ensure its immutability and security.

Dual-run preview — compare with live Symfony routes.