נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
23
חלקPart 4: OOP מתקדםAdvanced OOP כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

records, enums, sealed ו-pattern matchingrecords, enums, sealed & pattern matching

records לנתונים, enums עם התנהגות, sealed interfaces, ו-switch עם תבניות (Java 21).

records for data, enums with behavior, sealed interfaces, and switch with patterns (Java 21).

01המונחים של המפגשThis session's terms

לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.

Before the code, the words. Every term here is also linked in the course glossary.

  • record: record Book(String title, int year) {}: מחלקה בלתי משתנה לנתונים. Java כותבת לבד בנאי, title(), year(), equals, hashCode ו-toString (Book[title=Dune, year=1965]).record: record Book(String title, int year) {}: an immutable data class. Java writes the constructor, title(), year(), equals, hashCode and toString (Book[title=Dune, year=1965]) for you.
  • בנאי מקוצר: Book { if (year < 0) throw ...; } בתוך record: בנאי בלי רשימת פרמטרים, שרץ לפני שהשדות נקבעים. המקום לבדיקות.compact constructor: Book { if (year < 0) throw ...; } inside a record: a constructor with no parameter list, running before the fields are set. The place for checks.
  • enum: טיפוס עם רשימה סגורה של ערכים: enum Genre { NOVEL, SCIFI }. כל ערך הוא עצם יחיד, ואפשר להשוות עם ==. יכולים להיות לו שדות ומתודות.enum: A type with a closed list of values: enum Genre { NOVEL, SCIFI }. Each value is a single object, compared with ==. It can have fields and methods.
  • sealed: sealed interface Shape permits Circle, Rect: רק הטיפוסים שברשימה רשאים לממש. כך javac יודע את כל האפשרויות.sealed: sealed interface Shape permits Circle, Rect: only the listed types may implement it. That way javac knows every possibility.
  • switch עם תבניות: switch (s) { case Circle c -> ...; } בודק את הסוג ונותן משתנה מוכן. case ... when תנאי מוסיף תנאי.pattern switch: switch (s) { case Circle c -> ...; } checks the type and gives a ready variable. case ... when condition adds a condition.
  • פירוק record: case Rect(double w, double h) -> מפרק את ה-record לשדות שלו ישר בתוך ה-case.record pattern: case Rect(double w, double h) -> takes the record apart into its fields right in the case.
  • כיסוי מלא: switch שמחזיר ערך חייב לכסות כל אפשרות. עם sealed ו-enum javac בודק את זה, ואם הוספתם סוג חדש הוא מראה כל switch שצריך לעדכן.exhaustive: A switch that returns a value must cover every possibility. With sealed types and enums javac checks this, and when you add a new kind it points to every switch that needs updating.

02record: מחלקת נתונים בשורה אחתrecord: a data class in one line

record Book נותן toString, getters (title(), בלי get), ו-equals/hashCode לפי כל השדות, ולכן ה-Set רואה ספר אחד. הבנאי המקוצר בודק את השנה.

record Book gives a toString, getters (title(), no get), and equals/hashCode by every field, so the Set sees one book. The compact constructor checks the year.

Main.java
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Book a = new Book("Dune", 1965);
        Book b = new Book("Dune", 1965);
        System.out.println(a);
        System.out.println(a.title() + " " + a.equals(b));
        Set<Book> set = new HashSet<>(Set.of(a));
        set.add(b);
        System.out.println(set.size());
    }
}

record Book(String title, int year) {
    Book {
        if (year < 0) {
            throw new IllegalArgumentException("year must be >= 0, got " + year);
        }
    }
}
פלטOutput
Book[title=Dune, year=1965]
Dune true
1
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03enum עם התנהגותAn enum with behaviour

כל ערך של Genre נוצר פעם אחת עם הנתונים שלו. values() מחזירה את כולם לפי הסדר, ו-valueOf הופך טקסט לערך.

Each Genre value is created once with its data. values() returns them all in order, and valueOf turns text into a value.

Main.java
public class Main {
    public static void main(String[] args) {
        for (Genre g : Genre.values()) {
            System.out.println(g + " -> " + g.label() + ", loan " + g.loanDays() + " days");
        }
        Genre fav = Genre.valueOf("SCIFI");
        System.out.println(fav == Genre.SCIFI);
    }
}

enum Genre {
    NOVEL("Novel", 14),
    SCIFI("Science fiction", 14),
    COMIC("Comics", 7);

    private final String label;
    private final int loanDays;

    Genre(String label, int loanDays) {
        this.label = label;
        this.loanDays = loanDays;
    }

    String label() {
        return label;
    }

    int loanDays() {
        return loanDays;
    }
}
פלטOutput
NOVEL -> Novel, loan 14 days
SCIFI -> Science fiction, loan 14 days
COMIC -> Comics, loan 7 days
true
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

04sealed, records ו-switch עם תבניותsealed, records and a pattern switch

Shape סגור: יש רק Circle ו-Rect. ה-switch מפרק כל record (פירוק record), ו-when מוסיף תנאי (ריבוע). אין default: javac יודע שכיסינו הכול.

Shape is sealed: there's only Circle and Rect. The switch takes each record apart (record pattern), and when adds a condition (a square). There's no default: javac knows we covered everything.

Main.java
public class Main {
    static double area(Shape s) {
        return switch (s) {
            case Circle c -> Math.PI * c.r() * c.r();
            case Rect(double w, double h) when w == h -> w * w;
            case Rect(double w, double h) -> w * h;
        };
    }

    public static void main(String[] args) {
        Shape[] shapes = {new Circle(1), new Rect(2, 2), new Rect(2, 5)};
        for (Shape s : shapes) {
            System.out.println(s + " " + String.format("%.2f", area(s)));
        }
    }
}

sealed interface Shape permits Circle, Rect {
}

record Circle(double r) implements Shape {
}

record Rect(double w, double h) implements Shape {
}
פלטOutput
Circle[r=1.0] 3.14
Rect[w=2.0, h=2.0] 4.00
Rect[w=2.0, h=5.0] 10.00
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

05סוג חדש, switch ישןA new kind, an old switch

הוספנו Triangle לרשימת ה-permits, ושכחנו לעדכן את ה-switch. javac לא נותן לזה לעבור: זה היתרון של כיסוי מלא.

We added Triangle to the permits list and forgot to update the switch. javac won't let it pass: that's the payoff of exhaustiveness.

טעות נפוצהCommon mistake

סוג חדש, switch ישן

A new kind, an old switch

Main.java
public class Main {
    static double area(Shape s) {
        return switch (s) {
            case Circle c -> Math.PI * c.r() * c.r();
            case Rect r -> r.w() * r.h();
        };
    }

    public static void main(String[] args) {
        System.out.println(area(new Triangle(3, 4)));
    }
}

sealed interface Shape permits Circle, Rect, Triangle {
}

record Circle(double r) implements Shape {
}

record Rect(double w, double h) implements Shape {
}

record Triangle(double base, double height) implements Shape {
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:3: error: the switch expression does not cover all possible input values
        return switch (s) {
               ^
1 error
בעברית פשוטה: In plain words: the switch expression does not cover all possible input values: חסר case Triangle.the switch expression does not cover all possible input values: case Triangle is missing.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

06טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says

אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.

These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.

טעות נפוצהCommon mistake

צייד באגים: case חסר

Bug hunter: a missing case

Main.java
public class Main {
    static double area(Shape s) {
        return switch (s) {
            case Circle c -> Math.PI * c.r() * c.r();
            case Rect r -> r.w() * r.h();
        };
    }

    public static void main(String[] args) {
        System.out.println(area(new Triangle(3, 4)));
    }
}

sealed interface Shape permits Circle, Rect, Triangle {
}

record Circle(double r) implements Shape {
}

record Rect(double w, double h) implements Shape {
}

record Triangle(double base, double height) implements Shape {
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:3: error: the switch expression does not cover all possible input values
        return switch (s) {
               ^
1 error
בעברית פשוטה: In plain words: the switch expression does not cover all possible input values: Triangle ברשימת ה-permits אבל לא ב-switch.the switch expression does not cover all possible input values: Triangle is in the permits list but not in the switch.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

07הצעד של היום בפרויקט מדףToday's step in the Shelf project

sealed interface Item permits PrintBook, EBook, AudioBook, שלושתם records. describe(Item) עם פירוק records, ו-loanDays(Item) (ספר מודפס 14, ebook 21, ספר שמע 28 אם הוא מעל 600 דקות, אחרת 14). הדפיסו: Emma: print, 474 pages (14 days) / Dune: ebook, 2.5 MB (21 days) / Ulysses: audio, 12h30m (28 days).

sealed interface Item permits PrintBook, EBook, AudioBook, all three records. describe(Item) with record patterns, and loanDays(Item) (print 14, ebook 21, audio 28 if over 600 minutes, otherwise 14). Print: Emma: print, 474 pages (14 days) / Dune: ebook, 2.5 MB (21 days) / Ulysses: audio, 12h30m (28 days).

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

נבנה על ידיBuilt by Ariel Yohimovich