חלק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).
הנקודות החשובות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 Bookgives a toString, getters (title(), noget), and equals/hashCode by every field, so the Set sees one book.- הבנאי המקוצר בודק את השנה.The compact constructor checks the year.
- כל ערך של
Genreנוצר פעם אחת עם הנתונים שלו.EachGenrevalue is created once with its data. values()מחזירה את כולם לפי הסדר, ו-valueOfהופך טקסט לערך.values()returns them all in order, andvalueOfturns text into a value.Shapeסגור: יש רקCircleו-Rect.Shapeis sealed: there's onlyCircleandRect.- ה-switch מפרק כל record (פירוק record), ו-
whenמוסיף תנאי (ריבוע).The switch takes each record apart (record pattern), andwhenadds a condition (a square). - הוספנו
Triangleלרשימת ה-permits, ושכחנו לעדכן את ה-switch.We addedTriangleto thepermitslist 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 conditionadds 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 conditionadds 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 switch | 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. |
the switch expression does not cover all possible input valu | צייד באגים: case חסרBug hunter: a missing case | 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. |