4

As we know, we can't inherit final class in java but I want to know why java doesn't allow to do so? What is the reason behind it?

Vishal Patil
  • 195
  • 2
  • 13

4 Answers4

4

final specifically means "do not inherit me" (in this context, it has other meaning in different contexts).

The reason for developers to mark the class as final are mainly optimizations. Either they can guarantee that some variables will be specifically of some class and also JIT can take advantage of this as it can avoid more expensive virtual calls and rather inline the methods directly.

Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43
1

Because that was the objective of final keyword, i.e., to make the class not to be inherited. You can read this article:

Benefits of final keyword in Java

Here are few benefits or advantage of using final keyword in Java:

  1. Final keyword improves performance. Not just JVM can cache final variable but also application can cache frequently use final variables.

  2. Final variables are safe to share in multi-threading environment without additional synchronization overhead.

  3. Final keyword allows JVM to optimized method, variable or class.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

I think it is a reasonable request. Of course, the subclass shouldn't be able to override any behavior of the final super class. But the subclass can add its own, independent state and behavior. That is, we could weaken the final class semantics to mean all it methods are final, but the class can still be subclassed. This feature could become useful in some cases.

ZhongYu
  • 19,446
  • 5
  • 33
  • 61
0

Many OOP languages have this feature, C# for instance uses "sealed" to accomplish the same thing. In addition to the aforementioned compiler optimisations, it is also useful for enforcing certain constraints on the consumers of (e.g.) a class library where it is undesirable to allow the client code to override certain aspects of the libraries functionality for either security or protection of intellectual property reasons.