Java record in details with example

With Java 14 we have a new way to represent data intensive objects with less boilerplate codes.
Consider the following object representing Address and containing 5 fields. Address:{ street: city: zip: state: country: }
following record AddressRecord will be able to represent above address information.
AddressRecord
package Java14;

public record AddressRecord(String street, String city, Integer zip, String state, String country) {

}
We can instantiate AddressRecord record instance by passing the parameter values. Also system will generate the getter methods. The JVM will generate the getter methods for us. like, street() city() zip() state() country()
AddressRecordDemo
package Java14;

public class AddressRecordDemo {

	public static void main (String arg[]) {
		
		AddressRecord address1 = new AddressRecord("1044 Main Street", "Livermore", 94550, "CA", "USA");
		
		System.out.println(address1.street());
		System.out.println(address1.city());
		System.out.println(address1.state());
	}
}
Record can be very useful when we want to write DTO objects which is to carry or represent information. Following are some of the properties/rules that record have.
Rules for record
  • record can have Constructor.
  • record can have only static fields.
  • record cannot have instance field.
  • record can implement Interfaces.
  • We cannot extends record since implicitly it is final.

Can Java record be extended?

Java record introduced in java 14. It provides a way to reduce boiler plate code while defining data classes. record is final implicitly and cannot be extended.
For example in the following record MobilePhone, we cannot extend it.
record MobilePhone
record MobilePhone(String brand, String modelName, Number osVersion, boolean canFlip) {

}
Java records are implicitly final it can be confirmed by the following code. Which checks if the java.lang.Class for the object have final modifier or not.
RecordFinalTest
package Java14;

import java.lang.reflect.Modifier;

public class RecordFinalTest {

	public static void main(String[] args) {
		
		MobilePhone phone1 = new MobilePhone("Samsung", "Galaxy1", 1, false);

		//false
		System.out.println(Modifier.isFinal(phone1.getClass().getModifiers()));
		
		//false
		System.out.println(Modifier.isFinal(MobilePhone.class.getModifiers()));

	}

}
For more details about record in Java please check the following references.

References