We will deep dive into Java 16 Record to see how it helps us to reduce the boilerplate code of POJO classes.
POJO Boliterplate Code
No matter how many different POJOs you write, you have to write this 90% similar methods known as Boilerplate code.
How to Create a Java Record
public record Student (String name, int rollNo) {}
It requires the name of the Record and the fields you need in that record.
After defining parameters in the record, these fields will be private and immutable, meaning they will be private and final by default.
The Constructor of Java 16 Record
record Student (String name, int rollNo) {} // another record record Employee (String name, int id, List<String> skills) {}
This will be called like this,
Student student = new Student ("CodersTea", 1); var anotherStudent = new Student("Dev Tools by CodersTea", 2); var emp1 = new Employee("Imran", 1, List.of("nothing", "he knows nothing"))
Modify Default Constructor Initialization in Record
What if you want to do something in the constructor? Such as validation?
For this, we need to do the following.
record Student (String name, int rollNo) { public Student { Objects.requireNonNull(name); // non null name if ( rollNo < 1 ) { // not 0 or negative throw new IllegalArgumentException("Roll No can not be 0 or negative"); } } }
I declared a constructor-like block without a parameter bracket and wrote the logic there.
In this block, you can access the field directly with or without this keyword.
Getters in Java 16 Record
// gives us the name fields value String student1Name = student.name(); // skills field value List empSkills = emp1.skills(); // rollNo of student2 int student2RollNo = anotherStudent.rollNo();
It doesn’t use get as a prefix instead the field name with ().
toString Method in Java Record
System.out.println(student); System.out.println(emp1);
Output would be like,
Student[name=CodersTea, rollNo=1] Employee[name=Imran, id=1, skills=[nothing, he knows nothing]]
Inheritance in Java 16 Record
You can do inheritance in Java Record by implementing an interface, but can not extend other classes.
The reason is that a record internally converts to a class that extends Record.java,
and as you know multiple inheritances are not allowed in Java.
interface DemoInterface { void doSomething(); } record Student(String name, int rollNo) implements DemoInterface{ @Override public void doSomething() { // do something } }
That’s it . I have covered the basics of Record of Java 16.
It is just like a normal class but with special features.
It will greatly improve productivity and reduce the redundant code exponentially.