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

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

נקודה כ-recordA point as a record

תזכורת: מה ביקשוReminder: the task

record Point(int x, int y) עם מתודה distance() ומתודה withX(int) שמחזירה נקודה חדשה. הדפיסו את (3, 4), אחר כך 5.0 3, ואז true Point[x=0, y=4].

record Point(int x, int y) with a distance() method and a withX(int) method returning a new point. Print (3, 4), then 5.0 3, then true Point[x=0, y=4].

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעד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

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) {
        Point p = new Point(3, 4);
        System.out.println(p);
        System.out.println(p.distance() + " " + p.x());
        System.out.println(p.equals(new Point(3, 4)) + " " + p.withX(0));
    }
}

record Point(int x, int y) {
    double distance() {
        return Math.sqrt(x * x + y * y);
    }

    Point withX(int newX) {
        return new Point(newX, y);
    }
}
פלטOutput
Point[x=3, y=4]
5.0 3
true Point[x=0, y=4]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

דירוג שבודק את עצמוA rating that checks itself

תזכורת: מה ביקשוReminder: the task

record Rating(int value) עם בנאי מקוצר שזורק Rating must be 1-5, got 9. הדפיסו Rating[value=4] ואז את ההודעה עבור 9.

record Rating(int value) with a compact constructor throwing Rating must be 1-5, got 9. Print Rating[value=4] then the message for 9.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעד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

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println(new Rating(4));
        try {
            new Rating(9);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

record Rating(int value) {
    Rating {
        if (value < 1 || value > 5) {
            throw new IllegalArgumentException("Rating must be 1-5, got " + value);
        }
    }
}
פלטOutput
Rating[value=4]
Rating must be 1-5, got 9

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

גדלים ומחיריםSizes and prices

תזכורת: מה ביקשוReminder: the task

enum Size { SMALL(10), MEDIUM(14), LARGE(18) } עם price(). הדפיסו כל גודל ומחיר (SMALL 10), ואז Total: 42, biggest: LARGE.

enum Size { SMALL(10), MEDIUM(14), LARGE(18) } with price(). Print each size and price (SMALL 10), then Total: 42, biggest: LARGE.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעד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

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) {
        int total = 0;
        for (Size s : Size.values()) {
            System.out.println(s + " " + s.price());
            total += s.price();
        }
        System.out.println("Total: " + total + ", biggest: " + Size.values()[Size.values().length - 1]);
    }
}

enum Size {
    SMALL(10),
    MEDIUM(14),
    LARGE(18);

    private final int price;

    Size(int price) {
        this.price = price;
    }

    int price() {
        return price;
    }
}
פלטOutput
SMALL 10
MEDIUM 14
LARGE 18
Total: 42, biggest: LARGE

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

סוף שבועThe weekend

תזכורת: מה ביקשוReminder: the task

enum Day (ראשון עד שבת). static String kind(Day d) עם switch בחצים: שישי ושבת weekend, השאר workday. הדפיסו workday weekend, ואז 5 MONDAY (FRIDAY.ordinal() ו-valueOf).

enum Day (Sunday to Saturday). static String kind(Day d) with an arrow switch: Friday and Saturday weekend, the rest workday. Print workday weekend, then 5 MONDAY (FRIDAY.ordinal() and valueOf).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעד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

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    static String kind(Day d) {
        return switch (d) {
            case FRIDAY, SATURDAY -> "weekend";
            case SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY -> "workday";
        };
    }

    public static void main(String[] args) {
        System.out.println(kind(Day.SUNDAY) + " " + kind(Day.SATURDAY));
        System.out.println(Day.FRIDAY.ordinal() + " " + Day.valueOf("MONDAY"));
    }
}

enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
פלטOutput
workday weekend
5 MONDAY

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

צייד באגים: case חסרBug hunter: a missing case

תזכורת: מה ביקשוReminder: the task

התוכנית מהתזכורת לא מתקמפלת. הוסיפו case למשולש (בסיס × גובה ÷ 2) כך שיודפס 6.0.

The program from the refresher doesn't compile. Add a case for the triangle (base × height ÷ 2) so it prints 6.0.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

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

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

מסך הפלטOutput screen

צפו בהרצה צעד אחר צעד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

הפתרון המלא והפלט שלוFull solution and its output
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();
            case Triangle t -> t.base() * t.height() / 2;
        };
    }

    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 {
}
פלטOutput
6.0

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 6

מדף, צעד 23: סוגי פריטים כ-sealed ו-recordsShelf, step 23: item kinds as sealed types and records

תזכורת: מה ביקשוReminder: the task

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).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעד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

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.List;

public class Main {
    static String describe(Item item) {
        return switch (item) {
            case PrintBook(String title, int pages) -> title + ": print, " + pages + " pages";
            case EBook(String title, double mb) -> title + ": ebook, " + mb + " MB";
            case AudioBook(String title, int minutes) -> title + ": audio, " + minutes / 60 + "h" + minutes % 60 + "m";
        };
    }

    static int loanDays(Item item) {
        return switch (item) {
            case PrintBook p -> 14;
            case EBook e -> 21;
            case AudioBook a -> a.minutes() > 600 ? 28 : 14;
        };
    }

    public static void main(String[] args) {
        List<Item> shelf = List.of(new PrintBook("Emma", 474), new EBook("Dune", 2.5), new AudioBook("Ulysses", 750));
        for (Item it : shelf) {
            System.out.println(describe(it) + " (" + loanDays(it) + " days)");
        }
    }
}

sealed interface Item permits PrintBook, EBook, AudioBook {
}

record PrintBook(String title, int pages) implements Item {
}

record EBook(String title, double mb) implements Item {
}

record AudioBook(String title, int minutes) implements Item {
}
פלטOutput
Emma: print, 474 pages (14 days)
Dune: ebook, 2.5 MB (21 days)
Ulysses: audio, 12h30m (28 days)

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

איפה הנקודה?Where's the point?

תזכורת: מה ביקשוReminder: the task

static String where(Object o) עם switch על Object: נקודה בראשית (origin), על ציר x (on the x axis), על האלכסון (on the diagonal), נקודה אחרת (somewhere), מחרוזת (a string: hi), וכל השאר unknown. הדפיסו לכל אחד מ-(0,0), (5,0), (2,2), (1,7), "hi", 42.

static String where(Object o) with a switch on Object: a point at the origin (origin), on the x axis (on the x axis), on the diagonal (on the diagonal), another point (somewhere), a string (a string: hi), and anything else unknown. Print for each of (0,0), (5,0), (2,2), (1,7), "hi", 42.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעד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

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    static String where(Object o) {
        return switch (o) {
            case Point(int x, int y) when x == 0 && y == 0 -> "origin";
            case Point(int x, int y) when y == 0 -> "on the x axis";
            case Point(int x, int y) when x == y -> "on the diagonal";
            case Point p -> "somewhere";
            case String s -> "a string: " + s;
            default -> "unknown";
        };
    }

    public static void main(String[] args) {
        Object[] things = {new Point(0, 0), new Point(5, 0), new Point(2, 2), new Point(1, 7), "hi", 42};
        for (Object t : things) {
            System.out.println(where(t));
        }
    }
}

record Point(int x, int y) {
}
פלטOutput
origin
on the x axis
on the diagonal
somewhere
a string: hi
unknown

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

enum עם מתודה לכל ערךAn enum with a method per value

תזכורת: מה ביקשוReminder: the task

enum Op עם PLUS, MINUS, TIMES, סמל לכל אחד, ו-abstract int apply(int a, int b) שכל ערך מממש בגוף משלו. הדפיסו 6 + 3 = 9, 6 - 3 = 3, 6 * 3 = 18.

enum Op with PLUS, MINUS, TIMES, a symbol each, and abstract int apply(int a, int b) that each value implements in its own body. Print 6 + 3 = 9, 6 - 3 = 3, 6 * 3 = 18.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעד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

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) {
        for (Op op : Op.values()) {
            System.out.println("6 " + op.symbol() + " 3 = " + op.apply(6, 3));
        }
    }
}

enum Op {
    PLUS("+") {
        int apply(int a, int b) {
            return a + b;
        }
    },
    MINUS("-") {
        int apply(int a, int b) {
            return a - b;
        }
    },
    TIMES("*") {
        int apply(int a, int b) {
            return a * b;
        }
    };

    private final String symbol;

    Op(String symbol) {
        this.symbol = symbol;
    }

    String symbol() {
        return symbol;
    }

    abstract int apply(int a, int b);
}
פלטOutput
6 + 3 = 9
6 - 3 = 3
6 * 3 = 18

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

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