Task 3 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 — adding your own methods

Lesson

Запись — всё ещё класс

An empty body is the common case, but a record can hold methods like any class. What it cannot hold is mutable state: the components are fixed, so methods only compute from them.


Worked example

record Student(String name, int score) {
    String label() {
        return name + " (" + score + ")";
    }

    boolean passed() {
        return score >= 60;
    }
}

Inside the record the components are used by their plain names — name, score — without this. and without brackets.

Records fit naturally with streams: a list of records filtered and mapped reads almost like a sentence, which is what the next lessons build on.


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



Inside a record, a component is used as...


What can a record method NOT do?


Type exactly what this program prints.

record Item(String name, int price) {

    int withTax() {
        return price * 2;
    }
}

public class Main { public static void main(String[] a){
    Item i = new Item("pen", 5);
    System.out.println(i.withTax());
    System.out.println(i.name());
}}

A record with methods is useful when...


True or false?