Java 14 introduces a new class type record as preview feature to facilitate creation of immutable data objects. Java 15 enhances record type further. It is still a preview feature.
- Record object have implicit constructor with all the parameters as field variables.
- Record object have implicit field getter methods for each field variables.
- Record object have implicit field setter methods for each field variables.
- Record object have implicit sensible implementation of hashCode(), equals() and toString() methods.
- With Java 15, native methods cannot be declared in records.
- With Java 15, implicit fields of record are not final and modification using reflection will throw IllegalAccessException.
Example
Consider the following example −
ApiTester.java
public class APITester { public static void main(String[] args) { StudentRecord student = new StudentRecord (1, "Julie", "Red", "VI", 12); System.out.println(student.id()); System.out.println(student.name()); System.out.println(student); } } record StudentRecord(int id, String name, String section, String className, int age){}
Compile and Run the program
$javac -Xlint:preview --enable-preview -source 15 APITester.java $java --enable-preview APITester
Output
1 Julie StudentRecord[id=1, name=Julie, section=Red, className=VI, age=12]
To know more, Click Here.
Pingback: Java 15 - Text Blocks - Adglob Infosystem Pvt Ltd