Search code examples
javarecordjava-record

Is there any way of using Records with inheritance?


I have a bunch of @Data classes using Lombok and I want to migrate all of them to use the new Record functionality available in Java 14.

I know it's a little bit earlier but this is an experimental test that I'm doing.

The main problem here is involving inheritance. I have a class B which extends a class A. Is there any way of using Records with inheritance?


Solution

  • The JEP states this:

    Restrictions on records

    Records cannot extend any other class, and cannot declare instance fields other than the private final fields which correspond to components of the state description. Any other fields which are declared must be static. These restrictions ensure that the state description alone defines the representation.

    The Java 17 JLS 8.10 notes1 this:

    A record declaration does not have an extends clause, so it is not possible to explicitly declare a direct superclass type, even Record.

    However, a record can implement interfaces, so you can use them polymorphically. Furthermore, since records will inherit any default methods in the interfaces that they implement, they do support a limited form of inheritance.


    1 - This is a non-normative statement, but it is obviously true since the specified syntax for RecordDeclaration clearly does not allow extends to be used.