Welcome to our deep dive into Java Record Classes! This tutorial is designed to help both beginners and intermediate learners understand and utilize this powerful feature in Java.
Java Record Classes, introduced in Java 14, are a simple way to create immutable data classes. They offer a concise and efficient syntax for defining classes that store data and provide getter methods.
Serializable interface or provide getter/setter methods, making them more lightweight.Let's create a simple Person record class:
record Person(String name, int age) {
}In the above example, Person is our record class with two fields: name and age. No need to write getters, setters, or constructors!
To access the fields of a record class, simply use their names:
Person person = new Person("John", 30);
System.out.println(person.name()); // John
System.out.println(person.age()); // 30What is the purpose of a Java Record Class?
Let's create a Point record class with x and y fields:
record Point(int x, int y) {
public double distanceFromOrigin() {
return Math.sqrt(x * x + y * y);
}
}In this example, we've added a custom method distanceFromOrigin() that calculates the distance of the point from the origin.
Point point = new Point(3, 4);
System.out.println(point.distanceFromOrigin()); // 5.0Java Record Classes offer a concise and efficient way to create immutable data classes. They're perfect for representing simple data structures in your projects. Keep exploring and practicing with record classes to enhance your Java skills!
What is the main advantage of using Java Record Classes?