Task 1 of 5 · 0 solved · 5 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

11.3 Records — a class that is just data

Lesson

Класс, который ничего не делает, кроме хранения

Some classes exist only to hold a few values: a point, a name-and-score pair, a row from a file. Writing them the long way means a constructor, getters, equals and toString — a dozen lines in which nothing interesting happens.

A record replaces all of it with one line:

record Point(int x, int y) { }

Что появляется само

Point p = new Point(3, 4);
p.x()                  // 3      — accessor, note the brackets
System.out.println(p); // Point[x=3, y=4]
p.equals(new Point(3, 4));  // true — compares CONTENTS

Three things you would otherwise write by hand: accessors named after the fields, a readable toString, and an equals that compares the contents — exactly the one you had to write yourself in module 7.

Two rules: a record is immutable (no setters — the values are fixed at construction), and accessors are called x(), not getX(). Records need Java 16 or newer.


▶ Try it: run this, then change something and run it again.



A record automatically provides...


The accessor of a record field x is called...


Type exactly what this program prints.

record Box(String label, int size) { }

public class Main { public static void main(String[] a){
    Box b = new Box("hat", 7);
    System.out.println(b.label());
    System.out.println(b);
    System.out.println(b.equals(new Box("hat", 7)));
}}

Why has a record no setters?


True or false?