Java record in details with example

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.

No comments :

Post a Comment

Please leave your message queries or suggetions.