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 ensure that your class can be used safely in a multithreaded environment. If a class is not final, then it is possible for another thread to subclass it and override its methods in a way that could cause problems. By making the class final, you can guarantee that this cannot happen.

  • To improve the performance of your code. Because final classes cannot be subclassed, the Java compiler can apply certain optimizations to them that would not be possible otherwise. These optimizations can result in faster code execution.

It is important to note that while a final class cannot be subclassed, its methods can still be overridden if they are marked as final. This can be useful if you want to prevent certain methods from being overridden, but still allow others to be overridden.

Here is an example of a final class in Java:

final class MyClass {
  // class definition goes here
}

You can then use the class as you would any other class, but it cannot be subclassed.