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

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

מחלקות ועצמיםClasses & objects

מחלקה כתבנית ועצם כמופע, שדות ומתודות, new, והפניות בזיכרון (stack מול heap).

A class as a blueprint and an object as an instance, fields and methods, new, and references in memory (stack vs heap).

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

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

כתבו מחלקה Point עם שדות int x, int y ומתודה double distance() שמחזירה את המרחק מראשית הצירים (Math.sqrt(x*x + y*y)). צרו נקודה (3, 4) והדפיסו (3, 4) ואז 5.0.

Write a class Point with fields int x, int y and a method double distance() returning the distance from the origin (Math.sqrt(x*x + y*y)). Create the point (3, 4) and print (3, 4) then 5.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 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();
        p.x = 3;
        p.y = 4;
        System.out.println("(" + p.x + ", " + p.y + ")");
        System.out.println(p.distance());
    }
}

class Point {
    int x;
    int y;

    double distance() {
        return Math.sqrt(x * x + y * y);
    }
}
פלטOutput
(3, 4)
5.0

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

תרגילExercise 2

שני כלביםTwo dogs

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

מחלקה Dog עם name, age, מתודה String describe() שמחזירה למשל Rex is 3, ומתודה void birthday() שמעלה את הגיל. צרו את Rex (3) ואת Bella (1), חגגו יום הולדת ל-Bella, והדפיסו Rex is 3 ו-Bella is 2.

A class Dog with name, age, a method String describe() returning e.g. Rex is 3, and a method void birthday() raising the age. Create Rex (3) and Bella (1), give Bella a birthday, and print Rex is 3 and Bella is 2.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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) {
        Dog rex = new Dog();
        rex.name = "Rex";
        rex.age = 3;
        Dog bella = new Dog();
        bella.name = "Bella";
        bella.age = 1;
        bella.birthday();
        System.out.println(rex.describe());
        System.out.println(bella.describe());
    }
}

class Dog {
    String name;
    int age;

    String describe() {
        return name + " is " + age;
    }

    void birthday() {
        age++;
    }
}
פלטOutput
Rex is 3
Bella is 2

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

תרגילExercise 3

חשבון בנקA bank account

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

מחלקה Account עם int balance, void deposit(int amount) ו-boolean withdraw(int amount), שמושכת רק אם יש מספיק ומחזירה האם הצליחה. הפקידו 100, משכו 30 ואז 500, והדפיסו true 70 ו-false 70.

A class Account with int balance, void deposit(int amount) and boolean withdraw(int amount), which withdraws only if there's enough and returns whether it worked. Deposit 100, withdraw 30 then 500, and print true 70 and false 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();
        acc.deposit(100);
        System.out.println(acc.withdraw(30) + " " + acc.balance);
        System.out.println(acc.withdraw(500) + " " + acc.balance);
    }
}

class Account {
    int balance = 0;

    void deposit(int amount) {
        balance += amount;
    }

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

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

תרגילExercise 4

צייד באגים: מדף חצי ריקBug hunter: a half-empty shelf

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

התוכנית מהתזכורת קורסת עם NullPointerException. תקנו את הלולאה כך שעל תא ריק יודפס (empty): הפלט Dune ואז (empty).

The program from the refresher crashes with NullPointerException. Fix the loop so an empty cell prints (empty): the output Dune then (empty).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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) {
        Book[] shelf = new Book[2];
        shelf[0] = new Book();
        shelf[0].title = "Dune";
        for (Book b : shelf) {
            if (b != null) {
                System.out.println(b.title);
            } else {
                System.out.println("(empty)");
            }
        }
    }
}

class Book {
    String title;
}
פלטOutput
Dune
(empty)

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

תרגילExercise 5

לשנות או להחליף?Change or replace?

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

rename(book) משנה את השדה של הספר שקיבלה. replace(book) שמה בפרמטר שלה ספר חדש. מה ידפיס main? כתבו את הקוד, הריצו, וצפו בסימולציה. הפלט הנכון: Renamed ואז שוב Renamed.

rename(book) changes the field of the book it got. replace(book) puts a new book into its parameter. What will main print? Write the code, run it and watch the simulation. The right output: Renamed then Renamed 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 {
    static void rename(Book b) {
        b.title = "Renamed";
    }

    static void replace(Book b) {
        b = new Book();
        b.title = "Other";
    }

    public static void main(String[] args) {
        Book book = new Book();
        book.title = "Dune";
        rename(book);
        System.out.println(book.title);
        replace(book);
        System.out.println(book.title);
    }
}

class Book {
    String title;
}
פלטOutput
Renamed
Renamed

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

תרגילExercise 6

מדף, צעד 13: המחלקה BookShelf, step 13: the Book class

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

מחלקה Book עם title, author, year, ומתודות String line() (Emma by Austen (1815)) ו-boolean isClassic() (לפני 1950). שימו במערך את Emma (Austen, 1815), Dune (Herbert, 1965) ו-Ulysses (Joyce, 1922), הדפיסו שורה לכל ספר, ובסוף Classics: 2.

A class Book with title, author, year, and methods String line() (Emma by Austen (1815)) and boolean isClassic() (before 1950). Put Emma (Austen, 1815), Dune (Herbert, 1965) and Ulysses (Joyce, 1922) in an array, print a line per book, then Classics: 2.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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[] shelf = new Book[3];
        shelf[0] = new Book();
        shelf[0].title = "Emma";
        shelf[0].author = "Austen";
        shelf[0].year = 1815;
        shelf[1] = new Book();
        shelf[1].title = "Dune";
        shelf[1].author = "Herbert";
        shelf[1].year = 1965;
        shelf[2] = new Book();
        shelf[2].title = "Ulysses";
        shelf[2].author = "Joyce";
        shelf[2].year = 1922;
        int classics = 0;
        for (Book b : shelf) {
            System.out.println(b.line());
            if (b.isClassic()) {
                classics++;
            }
        }
        System.out.println("Classics: " + classics);
    }
}

class Book {
    String title;
    String author;
    int year;

    String line() {
        return title + " by " + author + " (" + year + ")";
    }

    boolean isClassic() {
        return year < 1950;
    }
}
פלטOutput
Emma by Austen (1815)
Dune by Herbert (1965)
Ulysses by Joyce (1922)
Classics: 2

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

אתגרChallenge 1

יומן טמפרטורותA temperature log

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

מחלקה TempLog עם מערך double[] values = new double[10], מונה int size, ומתודות add, max ו-average (רק על התאים שמולאו). הוסיפו 21.5, 25.0, 19.5 והדפיסו 3 readings, max 25.0, avg 22.0.

A class TempLog with an array double[] values = new double[10], a counter int size, and methods add, max and average (over the filled cells only). Add 21.5, 25.0, 19.5 and print 3 readings, max 25.0, avg 22.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 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) {
        TempLog log = new TempLog();
        log.add(21.5);
        log.add(25.0);
        log.add(19.5);
        System.out.println(log.size + " readings, max " + log.max() + ", avg " + log.average());
    }
}

class TempLog {
    double[] values = new double[10];
    int size = 0;

    void add(double v) {
        values[size] = v;
        size++;
    }

    double max() {
        double m = values[0];
        for (int i = 1; i < size; i++) {
            m = Math.max(m, values[i]);
        }
        return m;
    }

    double average() {
        double sum = 0;
        for (int i = 0; i < size; i++) {
            sum += values[i];
        }
        return sum / size;
    }
}
פלטOutput
3 readings, max 25.0, avg 22.0

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

אתגרChallenge 2

מלבן שיודע לגדולA rectangle that can grow

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

מחלקה Rect עם width, height ומתודות area(), perimeter(), isSquare() ו-Rect scaled(int k) שמחזירה מלבן חדש גדול פי k (המקורי לא משתנה). עבור 3x3 הדפיסו 9 true ואז 6x6 24.

A class Rect with width, height and methods area(), perimeter(), isSquare() and Rect scaled(int k) returning a new rectangle k times bigger (the original doesn't change). For 3x3 print 9 true then 6x6 24.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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) {
        Rect r = new Rect();
        r.width = 3;
        r.height = 3;
        Rect big = r.scaled(2);
        System.out.println(r.area() + " " + r.isSquare());
        System.out.println(big.width + "x" + big.height + " " + big.perimeter());
    }
}

class Rect {
    int width;
    int height;

    int area() {
        return width * height;
    }

    int perimeter() {
        return 2 * (width + height);
    }

    boolean isSquare() {
        return width == height;
    }

    Rect scaled(int k) {
        Rect r = new Rect();
        r.width = width * k;
        r.height = height * k;
        return r;
    }
}
פלטOutput
9 true
6x6 24

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

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