Java Record Classes

We’ll cover the following

  • Introduction
  • Feature of Record Classes
  • Restrictions on records
  • Java Record Syntax
  • Example

Introduction

Record classes are a new preview feature coming in Java 14 early next year. They are also sometimes known as Data classes. Let’s just say that even though its a preview feature be part of Java. Don’t let the preview status concern you. Features in pretty status may get minor changes as experience with them is gained but they are mostly going to be part of Java.

A record class declares a sequence of fields, and then the appropriate accessors, constructors, equals, hashCode, and toString methods are created automatically. The fields are final because the class is intended to serve as a simple “data carrier”.

Records are still classes and behave just like any class in Java. Declaring records will be with “record” keyword instead of regular “class”.

Features of Record Classes

Records are a new kind of type declaration in the Java language. Like an enum, a record is a restricted form of class. It declares its representation, and commits to an API that matches that representation. Records give up a freedom that classes usually enjoy: the ability to decouple API from representation. In return, records gain a significant degree of concision.

A record has a name and a state description. The state description declares the components of the record. Optionally, a record has a body. For example:

record Point(int x, int y) { }

Because records make the semantic claim of being simple, transparent holders for their data, a record acquires many standard members automatically:

  • A private final field for each component of the state description;
  • A public read accessor method for each component of the state description, with the same name and type as the component;
  • A public constructor, whose signature is the same as the state description, which initializes each field from the corresponding argument;
  • Implementations of equals and hashCode that say two records are equal if they are of the same type and contain the same state; and
  • An implementation of toString that includes the string representation of all the record components, with their names.

In other words, the representation of a record is derived mechanically and completely from the state description, as are the protocols for construction, deconstruction (accessors initially, and deconstruction patterns when we have pattern matching), equality, and display.

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.

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.

Java Record Syntax

RecordDeclaration:
  {ClassModifier} record TypeIdentifier [TypeParameters] 
    (RecordComponents) [SuperInterfaces] [RecordBody]
RecordComponents:
  {RecordComponent {, RecordComponent}}
RecordComponent:
  {Annotation} UnannType Identifier

Type annotations that modify the types of record components are propagated to the types in implicit declarations of mandated members (e.g., constructor parameters, field declarations, and method declarations).

RecordBody:
  { {RecordBodyDeclaration} }
RecordBodyDeclaration:
  ClassBodyDeclaration
  RecordConstructorDeclaration
RecordConstructorDeclaration:
  {Annotation} {ConstructorModifier} [TypeParameters] SimpleTypeName
    [Throws] ConstructorBody

Enhance the Java programming language with records. Records provide a compact syntax for declaring classes which are transparent holders for shallowly immutable data. This is a preview language feature in JDK 14.

Example:

public record Vehicle(String brand, String licensePlate) {}

Notice how the example uses the record instead of class. The record keyword is what tells the Java compiler that this type definition is a record.

package JAVA.Basic;

public class RecordsExample {

    public static void main(String[] args) {

        Vehicle vehicle = new Vehicle("Mercedes Maybach", "S 650 Guard");

        System.out.println(vehicle.brand());
        System.out.println(vehicle.licensePlate());

        System.out.println(vehicle.toString());

    }
}

Notice how the Java compiler has generated a brand() method, a licensePlate() method and a toString() method for us. The output printed from the above example would be:

That’s it!
You have successfully completed the post. Do Share : )

Peace Out!

Also Read – https://codingtimes.in/category/java/


Check Out Deals on -> Amazon , Flipkart , Myntra , Adidas , Apple TV , Boat , Canva , Beardo , Coursera , Cleartrip , Fiverr , MamaEarth , Swiggy


Leave a Reply

Your email address will not be published.