DEV Community

Discussion on: Why it is not possible to extend a final class in Java?

Collapse
 
martinhaeusler profile image
Martin Häusler

First of all, a final class can make sense. Imagine what would happen if somebody were to extend String, Integer or any of the other builtin classes - the JVM would be unable to perform a lot of optimizations. Sometimes, the programmer just didn't want to allow inheritance for architectural reasons. Granted, it's a rare occasion, but the possibility is there if you need it.

WARNING: VERY ADVANCED STUFF AHEAD
That being said, there actually is a possibility to inherit from a final class. This is needed mostly for internal purposes in frameworks like Spring of Hibernate. Using reflection, the final modifier of a class can be disabled at runtime, and the byte code of a class can be generated which extends the formerly final class. Don't try this at home.