Java 15 records
Java records
Java 15 introduced the record — they reduce the hassle of creating POJOs immensely.
The test
With the test code, we create an object Painting and assign Dimensions, testing the width corresponds with the test data:
import org.example.record.Dimensions;
import org.example.record.Painting;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class PaintingTest {
@Test
void testGetDimensions() {
var painting = new Painting(new Dimensions(12, 22));
assertEquals(22, painting.dimensions().width());
}
}
The code
Painting.java
package org.example.record;
public record Painting(Dimensions dimensions) {}
Dimensions.java*
package org.example.record;
public record Dimensions(int height, int width) {}
Summed up
With records, boilerplate class declarations, getters, equals and hashcode are replaced by a single record class declaration.
For more information, see Oracle’s Java 15 Java Language Updates.
* Ignoring that we haven’t specified a unit such as centimetre/inch