DEV Community

Cover image for Records in java
Bhagyashri Birajdar
Bhagyashri Birajdar

Posted on

Records in java

Introduction

In JAVA, record class is nothing but (immutable data) data carrying class between modules with the clear intention to reduce boilerplate code and achieve maximum efficiency.
Java Records is a feature introduced as a preview feature in Java 14 and became a standard feature in Java 16.

Reason behind why records introduced?

Before Java had record classes, if you wanted to create a class to hold data (like a person's name and id), you had to write a lot of repetitive code. This included making a constructor, getter and setter methods and if you want to print the contents of its objects as a string, we would need to override methods such as equals(), hashCode(), and toString().

let's understand above statement with example :-

Take a class 'person' with attributes for name and ID, providing methods to access these attributes and overriding methods like toString, hashCode, and equals for proper object representation, hashing, and value-based equality comparison respectively.


package p1;

import java.util.Objects;

class person {

    private final String name;
    private final int id;

// assinging values
    public person(String name, int id) {
        this.name = name;
        this.id = id;

    }

//for accesing values 
    public String getname() {
        return name;
    }

    public int getid() {
        return id;
    }

    // accessing content of object as string
    @Override
    public String toString() {
        return "person{" + "name=" + name + ", id='" + id + '\'' + '}';
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, id);
    }

    // to compare the value instead of mamory location
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        person pr = (person) obj;
        return id == pr.id && Objects.equals(name, pr.name);
    }

}
Enter fullscreen mode Exit fullscreen mode

The 'Data_carry' class for demonstrating object creation and comparison using these overridden methods to check if two 'person' objects hold the same values, not just memory locations, facilitating value-based comparisons in Java.


public class Data_carry {

    public static void main(String[] args) {
        person obj1 = new person("birajdar", 10);
        person obj2 = new person("birajdar", 10);
        System.out.println("name = " + obj1.getname() + "\n" + "id = " + obj1.getid());
        System.out.println(obj1);
        System.out.print(obj1.equals(obj2));

    }

}

Enter fullscreen mode Exit fullscreen mode

see, lot's of code we should write with simple java class to hold/carry some data.
To overcome this hadeche, JAVA introduced Recored class.

how to create record class?

  • Record class declaration part is slightly different from typical class declaration in java. means it quite similar to funtion.
  • Record class is create by using "record" keyword followed by "record_name" in its declaration.
  • In parentheses, parameters of this record class contain a comma separated list of fields.
  • Body of the record class is optional.

syntax :-


record record_name(List-of-fields){
// optional
}

Enter fullscreen mode Exit fullscreen mode

how record class works?

Record class reduce boilerplate code by automatically compiler generate standard implementations for common tasks like constructors, getter(), setter() methods to access data, equals(), hashCode(), and toString() methods to access content of object as string without any intervention of the programmer. This allows developers to focus on defining the data fields and their behavior.

let's understand record class with example :-


package p1;

record Person(String name,int id){}    // record class
public class Data
{
    public static void main( String[] args )
    {
        Person obj1 = new Person("birajdar", 10);
        Person obj2 = new Person("birajdar",10);

        System.out.println("name = " + obj1.name() + "\n" + "age = " + obj1.id());
        System.out.println(obj1);
        System.out.print(obj1.equals(obj2));


    }
}

Enter fullscreen mode Exit fullscreen mode

Explanation :-

In the above example a class 'Person' with name and ID attributes is created, showcasing object instantiation, attribute access, printing object details, and checking for equality in a concise and readable manner.

As we can see, we can reduce a complete class with a single line of code.

Important points about records

1) record class is immutable, meaning that once an object is created, its state cannot be changed.
2) A record class is instantiated by the new keyword, just like creating any other objects in Java.
3) records are implicitly final and cannot be extended by another class.
4) records cannot explicitly define additional instance variables beyond the automatically generated private final fields associated with their components.
5) Any other fields, except the list of components, must be declared static.
6) A record can implement one or more interface.
7) Records are serializable.

that's all about record now we will ready to learn, how record class and sealed interface works together? (prerequisite :- Sealed Interface)

Sealed interface with Record classes

To understand how record classes and sealed interfaces can work together, let's expand on the concept using an example.

let's consider an example where we create sealed interface "company" and then create record classes such as "manager" & "developer" that implement this interface & provide their own implementations for the info() method:


package p1;

sealed interface company permits Manager, developer {

    void work();
}

record Manager(String name, int age) implements company {

    @Override
    public void info() {
        System.out.println("Manager " + name + " (age: " + age + ") is managing teams.");

    }
}

record developer(String name, int age) implements company {

     @Override
    public void info() {
        System.out.println("Developer" + name + " (age: " + age + ") is working on coding tasks.");

    }
}

public class SealedInterface_RecordClass {
    public static void main(String[] args) {
        company obj1 = new Manager("paradox", 45);
        company obj2 = new developer("max", 30);

        obj1.info();
        obj2.info();
    }
}

Enter fullscreen mode Exit fullscreen mode

Advantages of Sealed Interfaces with Record Classes

1) Structural Consistency: Sealed interfaces maintain a controlled hierarchy by defining which classes can implement them.

2) Reduced Boilerplate: Records reduce repetitive code by and enhancing code readability.

3) Enhanced Readability: Sealed interfaces clarify class relationships, while records simplify the creation of immutable data models.

Thanks 🙏 for reading! Hopefully, this article helps you to understand Record class in Java. Please submit any suggestions or comments you may have in the comment section of this article.

Top comments (0)