Record
type is a new feature introduced in java 14 as a Preview Feature.
With Java 16, Record is an Standard feature to use immutable data sharead across components
java Record Type feature
Record Type
is specialized version and similar to a class, used to define an immutable class with data.
Let’s see difference between Class
and Record Type
.
For example, you want to transfer Employee data between Service layer ,data and web layer, You need to write the boiler plate code for below things
- create a Employee class
- Write a Constructor class
- add private and public members
- provide setters and getters for members
- Also need to write a logic for duplicate records using
equals
,hashcode
andtoString
methods.
Here is an example
package java16;
import java.util.Objects;
public class Employee {
// member fields
private Long id;
private String name;
// Constructor
public Employee(Long id, String name) {
this.id = id;
this.name = name;
}
public static void main(String[] args) {
Employee emp = new Employee(1l, "John");
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return Objects.equals(id, employee.id) && Objects.equals(name, employee.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public String toString() {
return "Employee{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
With above code, You need to write a boilerplate code and need to provide constructor,setter/getter, tostring and hascode changes for each member variable.
Let’s see how to do the same with Record Type that eliminate above steps and simplified code process.
Here is an syntax
public record name(fields);
Here is an example or a record with two fields
public record Employee(Long id,String name) {
}
Constructor delcared with paramters as given below
record Employee(String id, String name) {
// Implicitly declared fields
private final String id;
private final String name;
// Parameter Constructor
public Employee(String id, String name) {
this.id = id;
this.name = name;
}
}
Class members has inner record type in Java16
Java has inner classes supported inheritenly.
For example, classes defined inside a another classes are called as given below
class OuterClass{
class InnerClass{
}
}
Since java does not allow to declare static members inside a nested classes.
Record are static members, Java16 lifted to use Static members such as local interfaces, Enum and records used in nested inner classes.
public class RecordInner {
class InnerClass {
Employee book = new Employee(1l, "author");
}
}
record Employee(Long id,String name) {
}