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
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
This will be called like this,
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.
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
It doesn’t use get as a prefix instead the field name with ().
toString Method in Java Record
Output would be like,
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.
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.