נבנה על ידי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).

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • record: record Book(String title, int year) {}:record: record Book(String title, int year) {}:
  • בנאי מקוצר: Book { if (year < 0) throw ...; } בתוך record:compact constructor: Book { if (year < 0) throw ...; } inside a record:
  • 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.
  • כל ערך של Genre נוצר פעם אחת עם הנתונים שלו.Each Genre value is created once with its data.
  • values() מחזירה את כולם לפי הסדר, ו-valueOf הופך טקסט לערך.values() returns them all in order, and valueOf turns text into a value.
  • Shape סגור: יש רק Circle ו-Rect.Shape is sealed: there's only Circle and Rect.
  • ה-switch מפרק כל record (פירוק record), ו-when מוסיף תנאי (ריבוע).The switch takes each record apart (record pattern), and when adds a condition (a square).
  • הוספנו Triangle לרשימת ה-permits, ושכחנו לעדכן את ה-switch.We added Triangle to the permits list and forgot to update the switch.

מונחיםTerms

  • recordrecord: record Book(String title, int year) {}: מחלקה בלתי משתנה לנתונים. Java כותבת לבד בנאי, title(), year(), equals, hashCode ו-toString (Book[title=Dune, year=1965]).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.
  • בנאי מקוצרcompact constructor: Book { if (year < 0) throw ...; } בתוך record: בנאי בלי רשימת פרמטרים, שרץ לפני שהשדות נקבעים. המקום לבדיקות.Book { if (year < 0) throw ...; } inside a record: a constructor with no parameter list, running before the fields are set. The place for checks.
  • enumenum: טיפוס עם רשימה סגורה של ערכים: enum Genre { NOVEL, SCIFI }. כל ערך הוא עצם יחיד, ואפשר להשוות עם ==. יכולים להיות לו שדות ומתודות.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.
  • sealedsealed: sealed interface Shape permits Circle, Rect: רק הטיפוסים שברשימה רשאים לממש. כך javac יודע את כל האפשרויות.sealed interface Shape permits Circle, Rect: only the listed types may implement it. That way javac knows every possibility.
  • switch עם תבניותpattern switch: switch (s) { case Circle c -> ...; } בודק את הסוג ונותן משתנה מוכן. case ... when תנאי מוסיף תנאי.switch (s) { case Circle c -> ...; } checks the type and gives a ready variable. case ... when condition adds a condition.
  • פירוק recordrecord pattern: case Rect(double w, double h) -> מפרק את ה-record לשדות שלו ישר בתוך ה-case.case Rect(double w, double h) -> takes the record apart into its fields right in the case.
  • כיסוי מלאexhaustive: switch שמחזיר ערך חייב לכסות כל אפשרות. עם sealed ו-enum javac בודק את זה, ואם הוספתם סוג חדש הוא מראה כל switch שצריך לעדכן.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.
  • recordrecord: record Book(String title, int year) {}: מחלקה בלתי משתנה לנתונים. Java כותבת לבד בנאי, title(), year(), equals, hashCode ו-toString (Book[title=Dune, year=1965]).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.
  • בנאי מקוצרcompact constructor: Book { if (year < 0) throw ...; } בתוך record: בנאי בלי רשימת פרמטרים, שרץ לפני שהשדות נקבעים. המקום לבדיקות.Book { if (year < 0) throw ...; } inside a record: a constructor with no parameter list, running before the fields are set. The place for checks.
  • enumenum: טיפוס עם רשימה סגורה של ערכים: enum Genre { NOVEL, SCIFI }. כל ערך הוא עצם יחיד, ואפשר להשוות עם ==. יכולים להיות לו שדות ומתודות.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.
  • sealedsealed: sealed interface Shape permits Circle, Rect: רק הטיפוסים שברשימה רשאים לממש. כך javac יודע את כל האפשרויות.sealed interface Shape permits Circle, Rect: only the listed types may implement it. That way javac knows every possibility.
  • switch עם תבניותpattern switch: switch (s) { case Circle c -> ...; } בודק את הסוג ונותן משתנה מוכן. case ... when תנאי מוסיף תנאי.switch (s) { case Circle c -> ...; } checks the type and gives a ready variable. case ... when condition adds a condition.
  • פירוק recordrecord pattern: case Rect(double w, double h) -> מפרק את ה-record לשדות שלו ישר בתוך ה-case.case Rect(double w, double h) -> takes the record apart into its fields right in the case.
  • כיסוי מלאexhaustive: switch שמחזיר ערך חייב לכסות כל אפשרות. עם sealed ו-enum javac בודק את זה, ואם הוספתם סוג חדש הוא מראה כל switch שצריך לעדכן.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.

Cheatsheet

record: מחלקת נתונים בשורה אחתrecord: a data class in one line
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());
enum עם התנהגותAn enum with behaviour
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);
sealed, records ו-switch עם תבניותsealed, records and a pattern switch
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)));
}

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
the switch expression does not cover all possible input valuסוג חדש, switch ישןA new kind, an old switchthe 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.
the switch expression does not cover all possible input valuצייד באגים: case חסרBug hunter: a missing casethe 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.

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