Learn Java Records

ยท

4 min read

Records are a new addition to Java in version 16 that provides a simple and concise syntax for defining classes that are mainly used for data storage. Records have some unique features such as immutable components, implicit constructors, and more. In this guide, we'll explore what Records are, how they work, and how to use them in Java.

Table of Contents

  1. introduction to Records

  2. Creating Record

  3. Accessing Record Components

  4. Record Constructors

  5. Record Methods

  6. Inheritance with Records

  7. Record API Enhancements

  8. Best Practices for Using Records

  9. Conclusion

  10. Introduction to Records

    Records are a new type of class introduced in Java 16 that provide a concise syntax for defining classes that mainly serve as data storage. Records are essentially a set of data fields with a pre-defined behavior for the toString(), equals(), and hashCode() methods. Records are similar to classes but are immutable, meaning they can't be modified once created.

    Records are mainly used for storing data and are an ideal choice when you need to store a group of related fields together, and you don't need to add any complex behavior to the class.

  11. Creating Record

    Creating a Record in Java is easy. To define a Record, we use the record keyword, followed by the name of the Record, and a set of parentheses that contain the Record components. Here's an example:

    public record Person(String name, int age) {}
    

    This code creates a Record called Person, which has two components, a name and an age.

  12. Accessing Record Components

    Once we create a Record, we can access its components using the dot notation. For example:

    Person person = new Person("John", 30);
    System.out.println(person.name()); // John
    System.out.println(person.age()); // 30
    

    We can also create Immutable Records by using the final keyword before the component name:

    public record ImmutablePerson(final String name, final int age) {}
    

    In this case, the Record components are immutable, which means their values can't be changed once the Record is created.

  13. Record Constructors

    Records come with an implicit constructor that takes all of the Record components as parameters in the order they were defined. We can also define our own constructors for Records, but they must call the implicit constructor using the this keyword. Here's an example:

    public record Employee(String name, int age, double salary) {
        public Employee(String name, int age) {
            this(name, age, 0.0);
        }
    }
    

    In this example, we define a constructor that takes a nameand an age parameter, and sets the salaryto 0.0.

  14. Record Methods

    We can define our own methods in Records just like in regular classes. We can also define static methods in Records. Here's an example:

    public record Point(int x, int y) {
        public int distanceFromOrigin() {
            return (int) Math.sqrt(x * x + y * y);
        }
    
        public static Point origin() {
            return new Point(0, 0);
        }
    }
    

    In this example, we define two methods in the PointRecord: distanceFromOrigin() , which calculates the distance between the point and the origin, and origin(), which returns a new Point Record at the origin.

  15. Inheritance with Records

    Records can inherit from other classes and Records. However, there are some restrictions when it comes to inheritance. For example, a Record can't extend a class and a Record at the same time. Here's an example of Record inheritance:

    public record Employee(String name, int age, double salary) {}
    
    public record Manager(String name, int age, double salary, String team) 
    extends Employee(name, age, salary) {
    public Manager {
    if (team == null) throw new IllegalArgumentException("team can't be null");
    }
    }
    

    In this example, we define a ManagerRecord that extends theEmployeeRecord. TheManagerRecord has an additional component calledteam.

  16. Record API Enhancements

    Java 16 introduces some new methods that are specifically designed for Records. These methods include toUnmodifiableList(), which creates an unmodifiable List of the Record components, and "with" methods, which return a new Record with one or more components changed. Here's an example:

    public record Person(String name, int age) {}
    
    Person person = new Person("John", 30);
    List<Object> list = person.toUnmodifiableList();
    Person newPerson = person.withAge(40);
    

    In this example, we create a new PersonRecord, and use the toUnmodifiableList() method to create an unmodifiable List of the Record components. We also use the withAge()method to create a new PersonRecord with an updated age.

  17. Best Practices for Using Records

    When using Records, it's essential to keep them simple and use them only for data storage. Avoid adding any complex behavior to them, as this can make them harder to understand and maintain. Also, don't use Records for everything. Use them only when they make sense and when you need to store a group of related fields together.

  18. Conclusion

Records are an excellent addition to Java that provide a simple and concise syntax for defining classes that mainly serve as data storage. With their immutable components, implicit constructors, and new API enhancements, Records are an ideal choice for storing data in Java. Hopefully, this guide has given you a good understanding of what Records are, how they work, and how to use them in your Java projects.

Thanks for reading ๐Ÿ™‚

Did you find this article valuable?

Support Sylvester Amaechi by becoming a sponsor. Any amount is appreciated!