Search code examples
javainheritancerecord

Why Java records do not support inheritance?


Today I hit a wall, when I was about to add new functionality to the app. I had a record with data, but I needed some extra values. Adding this to the record would not make sense, becouse for most cases they will not be used and would be nulls, so I thought inheritance, which made perfect sense in this situation. But there is a problem , becouse Java records do not support inheritance, so I ended up with rewriting record to ugly POJO class with final values and getters.

So my question is basictly - why no inheritance. I understand there is not multiple inheritance becouse it's messy and hard to control on some point, but we also have final classes that cannot be inherited, why couldn't w e have records and final records?


Solution

  • See the corresponding JEP:

    Records are implicitly final, and cannot be abstract. These restrictions emphasize that the API of a record is defined solely by its state description, and cannot be enhanced later by another class or record.

    The components of a record are implicitly final. This restriction embodies an immutable by default policy that is widely applicable for data aggregates.

    The point is that reducing the realm of usage patterns, the compiler/JVM can do the sort of optimisations that the record concept is about.

    Meaning: if you allow for subclassing, the runtime will have to deal with polymorphism. Which is not the intention behind records.