Sunday, September 25, 2022

Java 14 records

Java 14 'records'

According to Oracle, Like an enum, a record is a restricted form of a class. It’s ideal for "plain data carriers," classes that contain data not meant to be altered and only the most fundamental methods such as constructors and accessors.
Note : This is a preview feature, which is a feature whose design, specification, and implementation are complete, but is not permanent, which means that the feature may exist in a different form or not at all in future JDK releases.

How to create a 'records' :

public record Employee(String name, int id) {}

Records are immutable data classes that require only the type and name of fields. The equals, hashCode, and toString methods, as well as the private, final fields and public constructor, are generated by the Java compiler

This is same as we create a POJO(Data) class Employee:

public class Employee {

private final int id;
private final String name;

public Employee(int id, String name) {

this.id = id;
this.name = name;
}

public int getId() {
return id;
}

public String getName() {
return name;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
  • We can create & access records  in the following way :
            Employee emp = new Employee("test",123);
            System.out.println(emp.name); // This will print test.
  • Records once created can not change because it is immutable.
  • Records can not extend any other class.
  • Records are implicit final in nature hence can not be inherit by another class.
  • Records can implements any interface.
  • Records provide canonical construct like 
            public Employee(int id, String name) {
this.id = id;
this.name = name;
    }
            But you can override and provide your custom constructor.

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home