DEV Community

Shelner
Shelner

Posted on

Java Record basics

// Q1.java
/*
 * This record automatically creates a class with private final fields,
 * a constructor, getters, equals(), hashCode(), and toString().
 */
public record Q1(String q, int num) {

    // You can also define your own methods if you want.
    public String ask() {
        return "Question No." + num + ": " + q;
    }
}
Enter fullscreen mode Exit fullscreen mode
// Main.java
public class Main {
    public static void main(String[] args) {
        // Create a new Q1 record (immutable object)
        Q1 q1 = new Q1("Is this q1?", 1);
        Q1 qq1 = new Q1("Is not this qq1?", 9);

        // Automatically generated getter methods
        System.out.println(q1.q());

        // Automatically generated toString()
        System.out.println(q1);

        // Automatically generated equals() and hashCode()
        System.out.println(q1.equals(qq1));

//        q1.num = 30; // Not allowed - record fields are final (immutable)

        // Custom method
        System.out.println(q1.ask());
    }
}
Enter fullscreen mode Exit fullscreen mode

Result

Is this q1?
Q1[q=Is this q1?, num=1]
false
Question No.1: Is this q1?

Top comments (0)