javarecordjava-record

Are records syntactic sugar for classes?


I recently discovered Java records, and it was amazing to learn about their existence and purpose.

However, I began to wonder if they are essentially just classes behind the scenes.

Does this mean that during compilation, they get converted into an explicit class with final private fields, a public constructor, and the necessary getters?


Solution

  • Under the hood it will still create a class (that's derived from java.lang.Record).

    You can try it out yourself:

    // test.java
    record Test(int foo, String bar) {}
    

    When you compile this with javac test.java and disassemble it again with javap Test you'll get this code:

    final class Test extends java.lang.Record {
      Test(int, java.lang.String);
      public final java.lang.String toString();
      public final int hashCode();
      public final boolean equals(java.lang.Object);
      public int foo();
      public java.lang.String bar();
    }