java compilation_error ai_generated true

error: records cannot extend classes

ID: java/records-cannot-extend-class

Also available as: JSON · Markdown · 中文
95%Fix Rate
85%Confidence
1Evidence
2024-05-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Java 16 active
Java 17 active
Java 21 active

Root Cause

Java records implicitly extend java.lang.Record and cannot extend any other class because they are final and their superclass is predetermined.

generic

中文

Java 记录隐式继承 java.lang.Record,不能继承其他任何类,因为它们是 final 的且超类是预定的。

Official Documentation

https://docs.oracle.com/en/java/javase/17/language/records.html

Workarounds

  1. 90% success Convert the record to a regular class that extends the desired class and manually implements equals, hashCode, toString, and a constructor. Example: `public class MyClass extends BaseClass { private final int x; public MyClass(int x) { this.x = x; } // plus equals/hashCode/toString }`
    Convert the record to a regular class that extends the desired class and manually implements equals, hashCode, toString, and a constructor. Example: `public class MyClass extends BaseClass { private final int x; public MyClass(int x) { this.x = x; } // plus equals/hashCode/toString }`
  2. 95% success Use composition instead of inheritance: have the record contain a field of the base class type. Example: `public record MyRecord(BaseClass base, int x) { }`
    Use composition instead of inheritance: have the record contain a field of the base class type. Example: `public record MyRecord(BaseClass base, int x) { }`
  3. 85% success If you need the base class functionality, create an interface that the base class implements, and have the record implement that interface instead.
    If you need the base class functionality, create an interface that the base class implements, and have the record implement that interface instead.

中文步骤

  1. 将记录转换为继承所需类的普通类,并手动实现 equals、hashCode、toString 和构造函数。示例:`public class MyClass extends BaseClass { private final int x; public MyClass(int x) { this.x = x; } // 加上 equals/hashCode/toString }`
  2. 使用组合而非继承:让记录包含基类类型的字段。示例:`public record MyRecord(BaseClass base, int x) { }`
  3. 如果需要基类功能,创建一个基类实现的接口,然后让记录实现该接口。

Dead Ends

Common approaches that don't work:

  1. Remove the 'record' keyword and make it a regular class that extends the desired class. 70% fail

    This loses all record features (canonical constructor, equals/hashCode/toString), requiring manual implementation and breaking serialization behavior.

  2. Use 'implements' instead of 'extends' on the record. 90% fail

    Records can implement interfaces but not extend classes; the error message is about extending classes, not interfaces.

  3. Make the record abstract to allow extending. 100% fail

    Records cannot be abstract; the compiler will reject with 'illegal combination of modifiers: abstract and final'.