Is there any way of using Records with inheritance?

Viewed 12393

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?

2 Answers

Is there any way of using records with inheritance?

Records already extend java.lang.Record. As Java does not allow multiple inheritance, records cannot extend any other class.

Consider, for example, the following record Point:

public record Point(double x, double y) {}

You can compile it using:

javac --enable-preview -source 14 Point.java

With the help of javap, you can can have details about the code generate for Point:

javap -p Point

The output will be:

Compiled from "Point.java"
public final class Point extends java.lang.Record {
  private final double x;
  private final double y;
  public Point(double, double);
  public java.lang.String toString();
  public final int hashCode();
  public final boolean equals(java.lang.Object);
  public double x();
  public double y();
}

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.

However, they can implement interfaces and define instance methods, so you can use them polymorphically. Furthermore, since they will inherit default methods, they do support a limited form of inheritance.

At this time, the Java Language Specification does not specify the record construct and its semantics.

Related