In this tutorial you’ll learn about a new way of creating class using record
keyword in Java which has become a
feature from Java 16.
Many a time we create classes meant for storing data. Such Bean classes are not meant to be altered and consists of constructors and accessor methods (getters and setters) which are sufficient to make such classes act like "plain data carriers".
Here is an example of Person class with fields name, gender and age.
public class Person { private String name; private char gender; private int age; Person(String name, char gender, int age){ this.name = name; this.gender = gender; this.age = age; } public String getName() { return name; } public char getGender() { return gender; } public int getAge() { return age; } }
As you can see a lot of code is required just to create a class meant as a data carrier.
Record classes in Java are a way to create such classes with just a single line of code.
Java record keyword
record keyword in Java is a new kind of type declaration which helps in creating a class.
You just need to declare a record with a name and a description of its contents.
The appropriate constructor, accessors, equals, hashCode, and toString methods are generated automatically. For example, Person class as described above can be defined using record as given below.
public record Person(String name, char gender, int age) {}
That’s all you need to create a Person class. A record consists of a name (Person in our example) and a list of the record's components (which in this example are String name, char gender and int age).
This Person class created using record generates the following members automatically.
- All fields specified in the record are declared as private final fields. So in
Person
record class given fields will be declared automatically. - public accessors methods for the fields having the same name and type as field name.
- A constructor having the same name as the name used with record keyword. Constructor parameters are same as the record’s component list.
- Implementations of the equals() and hashCode() methods
- An implementation of the toString method that includes the string representation of all the record class's components, with their names.
Creating instance of record
As record classes are just special kinds of classes, you create a record object with the new keyword same way you create an instance of normal class.
public class PersonMain { public static void main(String[] args) { Person person = new Person("Dinesh", 'M', 32); System.out.println("Name- " + person.name()); System.out.println("Gender- " + person.gender()); System.out.println("Age- " + person.age()); } }
Output
Name- Dinesh Gender- M Age- 32
Important points about record
1. In order to have a better idea about generated class by using record keyword let’s use javap to disassemble class file.
D:\NETJS\NetJS_2017\JavaWS>javap Person.class Compiled from "Person.java" public final class com.netjstech.Person extends java.lang.Record { public com.netjstech.Person(java.lang.String, char, int); public java.lang.String name(); public char gender(); public int age(); public final java.lang.String toString(); public final int hashCode(); public final boolean equals(java.lang.Object); }You can see that the generated class is final which means it can’t be subclassed.
2. Any class created using record extends java.lang.Record
which is the common base class of all Java language record
classes.
3. If you want to add your own constructor in a record class that is permissible.
public record Person(String name, char gender, int age) { public Person(String name, char gender, int age){ if(name.isBlank() || age < 1) { throw new java.lang.IllegalArgumentException("Name can't be left blank and age should be atleast 1"); } this.name = name; this.gender = gender; this.age = age; } }
4. You can also add a compact constructor where the constructor’s signature is derived from the record’s components. For example constructor as shown above can also be written in the following compact form.
public record Person(String name, char gender, int age) { public Person{ if(name.isBlank() || age < 1) { throw new java.lang.IllegalArgumentException("Name can't be left blank and age should be atleast 1"); } } }
5. You can declare static fields, static initializers, and static methods in a record class, and they behave as they would in a normal class.
public record Person(String name, char gender, int age) { static String country; static { country = "India"; } public static void displayCountry() { System.out.println("Country- " + country); } }
public class PersonMain { public static void main(String[] args) { Person person = new Person("Dinesh", 'M', 32); System.out.println(person); Person.displayCountry(); } }
Output
Person[name=Dinesh, gender=M, age=32] Country- India
6. You cannot declare instance variables or initializer blocks in a record class.
public record Person(String name, char gender, int age) { String country; // initializer block { country = "India"; } }This results in compile time error-
User declared non-static fields country are not permitted in a record
7. You can add instance methods in a record class.
public record Person(String name, char gender, int age) { public void displayPersonDetails() { System.out.println("Name- " + name()); System.out.println("Gender- " + gender()); System.out.println("Age- " + age()); } }
public class PersonMain { public static void main(String[] args) { Person person = new Person("Dinesh", 'M', 32); person.displayPersonDetails(); } }
Output
Name- Dinesh Gender- M Age- 32
8. Java record was added as a preview feature in Java 14 (JEP 359). Became a finalized feature in Java 16 (JEP 395).
That's all for this topic Java Record Class With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Advanced Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment