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

JavaJava
15
חלקPart 3: OOP: היסודותOOP: the basics כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

Encapsulation, getters, setters ו-immutabilityEncapsulation, getters, setters & immutability

private ו-public, שמירה על מצב תקין, getters ו-setters במידה, ועצמים שלא משתנים.

private and public, keeping state valid, getters and setters in moderation, and objects that never change.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.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

מדחוםA thermometer

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

מחלקה Thermometer עם private double celsius, getCelsius(), getFahrenheit() (מחושב, בלי שדה), ו-setCelsius שזורקת IllegalArgumentException מתחת ל-273.15-. קבעו 25, הדפיסו 25.0C = 77.0F, נסו 300- (ב-catch הדפיסו Rejected: והודעה), והדפיסו שוב את הצלזיוס.

A class Thermometer with private double celsius, getCelsius(), getFahrenheit() (computed, no field), and setCelsius throwing IllegalArgumentException below -273.15. Set 25, print 25.0C = 77.0F, try -300 (in the catch print Rejected: and the message), and print the celsius again.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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) {
        Thermometer t = new Thermometer();
        t.setCelsius(25);
        System.out.println(t.getCelsius() + "C = " + t.getFahrenheit() + "F");
        try {
            t.setCelsius(-300);
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
        System.out.println(t.getCelsius());
    }
}

class Thermometer {
    private double celsius;

    double getCelsius() {
        return celsius;
    }

    double getFahrenheit() {
        return celsius * 9 / 5 + 32;
    }

    void setCelsius(double c) {
        if (c < -273.15) {
            throw new IllegalArgumentException("below absolute zero: " + c);
        }
        celsius = c;
    }
}
פלטOutput
25.0C = 77.0F
Rejected: below absolute zero: -300.0
25.0

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

תרגילExercise 2

צייד באגים: מיליונר בקיצור דרךBug hunter: a shortcut millionaire

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

main מנסה לשים מיליון ישירות ביתרה, ו-javac עוצר. תקנו את main כך שיפקיד 100 דרך המתודה, ויודפס 100.

main tries to put a million straight into the balance, and javac stops it. Fix main to deposit 100 through the method, so it prints 100.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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 {
    public static void main(String[] args) {
        Account acc = new Account();
        acc.deposit(100);
        System.out.println(acc.getBalance());
    }
}

class Account {
    private int balance = 0;

    void deposit(int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("amount must be positive");
        }
        balance += amount;
    }

    int getBalance() {
        return balance;
    }
}
פלטOutput
100

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

תרגילExercise 3

חשבון מוגןA protected account

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

Account עם private final String owner (מהבנאי), private int balance, ו: deposit (זורקת על סכום לא חיובי), withdraw (מחזירה false על סכום לא חיובי או גדול מהיתרה), getOwner, getBalance. בלי setter ליתרה. הפקידו 100 ל-Noa, משכו 30 ו-500, והדפיסו true false ו-Noa: 70.

Account with private final String owner (from the constructor), private int balance, and: deposit (throws on a non-positive amount), withdraw (returns false on a non-positive amount or one larger than the balance), getOwner, getBalance. No setter for the balance. Deposit 100 for Noa, withdraw 30 and 500, and print true false and Noa: 70.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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) {
        Account acc = new Account("Noa");
        acc.deposit(100);
        System.out.println(acc.withdraw(30) + " " + acc.withdraw(500));
        System.out.println(acc.getOwner() + ": " + acc.getBalance());
    }
}

class Account {
    private final String owner;
    private int balance;

    Account(String owner) {
        this.owner = owner;
    }

    String getOwner() {
        return owner;
    }

    int getBalance() {
        return balance;
    }

    void deposit(int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("amount must be positive");
        }
        balance += amount;
    }

    boolean withdraw(int amount) {
        if (amount <= 0 || amount > balance) {
            return false;
        }
        balance -= amount;
        return true;
    }
}
פלטOutput
true false
Noa: 70

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

תרגילExercise 4

נקודה שלא זזהA point that doesn't move

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

כתבו את Point הבלתי משתנה מהתזכורת (שדות private final, x(), y(), moveBy). הזיזו את (1, 2) ב-(10, 0) ואז ב-(0, 5), בשרשרת אחת, והדפיסו 1,2 -> 11,7.

Write the immutable Point from the refresher (private final fields, x(), y(), moveBy). Move (1, 2) by (10, 0) and then by (0, 5), in one chain, and print 1,2 -> 11,7.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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(1, 2);
        Point q = p.moveBy(10, 0).moveBy(0, 5);
        System.out.println(p.x() + "," + p.y() + " -> " + q.x() + "," + q.y());
    }
}

final class Point {
    private final int x;
    private final int y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    int x() {
        return x;
    }

    int y() {
        return y;
    }

    Point moveBy(int dx, int dy) {
        return new Point(x + dx, y + dy);
    }
}
פלטOutput
1,2 -> 11,7

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

תרגילExercise 5

טווח חוקיA valid range

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

מחלקה בלתי משתנה Range(int min, int max) שהבנאי שלה זורק min 5 > max 1 כשהסדר הפוך. מתודות contains(int) ו-length(). הדפיסו עבור 10–20 את true false 10, ואחר כך את ההודעה של new Range(5, 1).

An immutable class Range(int min, int max) whose constructor throws min 5 > max 1 when the order is reversed. Methods contains(int) and length(). For 10–20 print true false 10, then the message of new Range(5, 1).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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) {
        Range r = new Range(10, 20);
        System.out.println(r.contains(15) + " " + r.contains(25) + " " + r.length());
        try {
            new Range(5, 1);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

class Range {
    private final int min;
    private final int max;

    Range(int min, int max) {
        if (min > max) {
            throw new IllegalArgumentException("min " + min + " > max " + max);
        }
        this.min = min;
        this.max = max;
    }

    boolean contains(int n) {
        return n >= min && n <= max;
    }

    int length() {
        return max - min;
    }
}
פלטOutput
true false 10
min 5 > max 1

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

תרגילExercise 6

מדף, צעד 15: דירוג תמיד בין 1 ל-5Shelf, step 15: a rating always 1–5

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

ל-Book יש private final String title ו-private int rating = 3, getters, ו-setRating שזורקת Rating must be 1-5, got 7. קבעו 4, נסו 7 (הדפיסו את ההודעה), והדפיסו Dune 4.

Book has private final String title and private int rating = 3, getters, and setRating throwing Rating must be 1-5, got 7. Set 4, try 7 (print the message), and print Dune 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) {
        Book b = new Book("Dune");
        b.setRating(4);
        try {
            b.setRating(7);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
        System.out.println(b.getTitle() + " " + b.getRating());
    }
}

class Book {
    private final String title;
    private int rating = 3;

    Book(String title) {
        this.title = title;
    }

    String getTitle() {
        return title;
    }

    int getRating() {
        return rating;
    }

    void setRating(int rating) {
        if (rating < 1 || rating > 5) {
            throw new IllegalArgumentException("Rating must be 1-5, got " + rating);
        }
        this.rating = rating;
    }
}
פלטOutput
Rating must be 1-5, got 7
Dune 4

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

אתגרChallenge 1

כסף בלי שגיאות עיגולMoney without rounding errors

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

מחלקה בלתי משתנה Money ששומרת long cents (ולא double, שמעגל). מתודות plus(Money), times(int) ו-format() (12.50). חשבו 12.50 כפול 3 ועוד 0.99, והדפיסו 12.50 x3 + 0.99 = 38.49.

An immutable class Money storing long cents (not a double, which rounds). Methods plus(Money), times(int) and format() (12.50). Compute 12.50 times 3 plus 0.99, and print 12.50 x3 + 0.99 = 38.49.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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) {
        Money price = new Money(1250);
        Money total = price.times(3).plus(new Money(99));
        System.out.println(price.format() + " x3 + 0.99 = " + total.format());
    }
}

final class Money {
    private final long cents;

    Money(long cents) {
        this.cents = cents;
    }

    Money plus(Money other) {
        return new Money(cents + other.cents);
    }

    Money times(int n) {
        return new Money(cents * n);
    }

    String format() {
        return (cents / 100) + "." + String.format("%02d", cents % 100);
    }
}
פלטOutput
12.50 x3 + 0.99 = 38.49

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

אתגרChallenge 2

רשימה שאי אפשר לשנות מבחוץA list nobody changes from outside

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

Playlist מחזיקה private final List<String> songs. add דוחה שם ריק. getSongs() מחזירה עותק לקריאה בלבד (List.copyOf). ב-main הוסיפו שני שירים, נסו להוסיף דרך הרשימה שקיבלתם (ב-catch של UnsupportedOperationException הדפיסו can't change it from outside), והדפיסו [Song A, Song B].

Playlist holds private final List<String> songs. add rejects an empty name. getSongs() returns a read-only copy (List.copyOf). In main add two songs, try adding through the list you got (in a catch of UnsupportedOperationException print can't change it from outside), and print [Song A, Song B].

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Playlist p = new Playlist();
        p.add("Song A");
        p.add("Song B");
        List<String> view = p.getSongs();
        try {
            view.add("Hack");
        } catch (UnsupportedOperationException e) {
            System.out.println("can't change it from outside");
        }
        System.out.println(p.getSongs());
    }
}

class Playlist {
    private final List<String> songs = new ArrayList<>();

    void add(String song) {
        if (song == null || song.isBlank()) {
            throw new IllegalArgumentException("empty song name");
        }
        songs.add(song);
    }

    List<String> getSongs() {
        return List.copyOf(songs);
    }
}
פלטOutput
can't change it from outside
[Song A, Song B]

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

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